5 ms·
Elegantly solving the wrong problem is not elegant, though. strcmp is a comparison. Comparisons are intuitively boolean unless there's a clear reason to be oth
by PhasmaFelis 10y ago
Elegantly solving the wrong problem is not elegant, though.
strcmp is a comparison. Comparisons are intuitively boolean unless there's a clear reason to be otherwise, and "false=0, true=nonzero" is well-known. Therefore, "strcmp('foo', 'foo')" shouldn't return 0 any more than "5 == 5" should return 0.
If the function were called "strsub" or "strdiff" and was described as taking the difference of two strings, then this might be an elegant solution, but "comparison" means something specific in a programming context, and this isn't it.
- rabidrat 10y agoIn an assembly context, cmp means 'set the flags as though you subtracted but don't do the subtraction'. This particular misdesign is from before C.
- ArkyBeagle 10y agoI blame Ben Franklin for guessing wrong about the sign of the charge of the electron. (I keed, I keed )
- userbinator 10y agoComparisons are intuitively boolean Are comparisons in general boolean? I think specific operators are, but that's because they are asking a particular boolean question. A general "compare X and Y" doesn't seem like it should ever be "true" or "false" (because what would those mean? Different --- in what way, less, greater, or both --- or equal?) As the sibling comment alludes to, comparisons are really a form of subtraction to the hardware, and C makes this fact very obvious.
- ArkyBeagle 10y agoWhen you get access to a time machine, go back in time and have this argument with the poor grad student who committed this sin :) In assembler, comparisons generally have a result of zero when things are the same because hardware works that way. If the difference between two voltages is zero, they "null" and are the same. In a pidgin, non-real assembler I'm making up: MOV AX,A_VARIABLE MOV BX,B_VARIABLE CMP AX,BX ;; or maybe AND AX,BX or XOR AX,BX because flags JNE THEY_ARE_NOT_EQUAL JMP THEY_ARE_EQUAL ... THEY_ARE_EQUAL: ... THEY_ARE_NOT_EQUAL: In 'C' if I am really concerned about this, I will: const bool TheThingMatches = (strcmp(a,b)==0); Edit: It ate my line breaks.
- new_hackers 10y ago> Comparisons are intuitively boolean unless there's a clear reason to be otherwise To support sorting. The result of a "comparison" does not imply the testing for equality or equivalence. I can "compare" lots of things, and my results are not strictly boolean. A "comparison" often implies one thing is "better" or "worse" or the "same" as another thing.