3 ms·
Visually it is confusing. The goal is to test for equality but there is the "!" (not) operator in there, so my brian translates it quickly to "not equal" That
by rdtsc 10y ago
Visually it is confusing. The goal is to test for equality but there is the "!" (not) operator in there, so my brian translates it quickly to "not equal"
That is why I always write == 0 on comparison even if it is longer. It removes a negative and makes it clear.
- userbinator 10y ago> The goal is to test for equality If it helps, you should think of strcmp() as returning a difference. strcmp() means "string comparison", and to compare is to find differences. Thus the "not" means "no difference", just as the idiom "if(!p)" means "there is no (object pointed to by) p". That is why I always write == 0 on comparison even if it is longer. It removes a negative and makes it clear. Seeing "== 0" for that in C for me is actually like seeing the equivalent of "== false" in languages that have booleans: the extra comparison causes a bit of pondering at whether it was really what the programmer intended. The if(...) is already an implicit comparison with 0/nonzero. I've seen things like this too, presumably written by someone who wanted to make the comparison really explicit, but just ends up causing more confusion IMHO: if ((strcmp(a, b) == 0) != false) { /* does this code get executed when the strings are equal or different? */ }
- carsondk 10y agoI'm not actually advocating for this change, but at least to me this would intuitively make sense if the function were named instead after "string contrast".
- rdtsc 10y agoWell to each its own, or however the saying goes. Because strcmp() returns a difference, as you said, i.e. a number comparing it a number "== 0" makes most sense to me. > "not" means "no difference I'd rather see less "not"s, it is easier to reason about. "not" means logical expressions to me, strcmp returns numbers, I would rather keep ! away. > "if(!p)" means "there is no (object pointed to by) p". Ok, now we have pointer in play. strcmp really does return numbers. Why bring pointers or logic operators, doesn't that confuse things? It does for me. > ((strcmp(a, b) == 0) != false) I have never seen that. And would never advocate for that, why are we doing it that way again?
- lfowles 10y ago>> ((strcmp(a, b) == 0) != false) >I have never seen that. And would never advocate for that, why are we doing it that way again? I think a more reasonable example would be (with some reasonably namespaced define, blah blah blah): strcmp(a, b) == CMP_EQUAL;
- Konfituren 10y agoSo you're trying to imply your logical inversion prevents bad coding habits? What happens when people actually do start using !strcmp() and then add an additional != false anyway? Your example doesn't show that it's hard to understand what ==0 means, it shows that some people don't understand booleans, which is no less true of your method than the other.
- deleted 10y ago[deleted]