Rod Pemberton said:
Determining if strings are equal or different is useful. However,
determining if the last compared character in one string was above (>0) or
below (<0) the last compared character in the other, is useless and heavily
dependent on the nonportable and sometimes random ordering of the character
set. Because of this, I'd posit that strcmp() is _essentially_ a boolean
function: zero equal, non-zero if different.
strcmp() gives a consistent ordering of string values. Sometimes an
internally consistent ordering is all you need, for example if you
want to build a search tree.
strcmp() is not a boolean function.
Untrue. There is an entire generation of programmers who were taught not to
think in terms of 'true'. They were taught to think entirely in terms of
'false'. 'true' is thought of as 'not false' and 'false' is zero (for all
but a few languages, i.e., ADA which, IIRC, Keith has experience in...). An
if() statement is thought of as 'if(not false)' or 'if(not zero)'. Since
strcmp() returns zero for equality, if(!strcmp()) says 'if(not zero)' which
is understood to be 'true'. if(strcmp()==0), on the other hand says 'if(0
is equal to 0)'. This, of course, lacks the simplicity, elegance, and
mnemonic of 'if(not zero)'.
Yes, in C zero is false, and any non-zero value is true, so a boolean
value should be used directly as a condition, not compared for
equality to either true or false. Something like "if (b == true)" is
both dangerous and unnecessarily verbose; "if (b == false)" happens
not to be as dangerous (because there's only a single false value),
but it's just as unnecessarily verbose. They should be "if (b)" and
"if (!b)", respectively.
But that applies only when b is a boolean value. The result returned
by strcmp() is not.
If you want to define macros like
#define STR_EQ (strcmp((x), (y)) != 0)
#define STR_NE (strcmp((x), (y)) == 0)
then of course you can use them as conditions.
(Aside: I've never heard of a language called "ADA". I've programmed
in Ada. It's a name, not an acronym.)
True. They are not programming in ADA and don't need to separate boolean
false and zero as distinct values.
Which has no relevance to what we're actually discussing.
If you want to argue that it's acceptable to treat the result of
strcmp() as a boolean value (true if the arguments are unequal, false
if they're equal), that's not an entirely unreasable argument. I
don't happen to agree with it (if strcmp() were intended to be boolean
it would have a different name), but I recognize that some programmers
either value terseness over clarity, or just don't find !strcmp(x, y)
as unclear as I do. Bringing in an irrelevant argument about true and
false doesn't help your case.