The strcmp()
function is only defined to return a negative value if argument 1 precedes argument 2, zero if they're identical, or a positive value if argument 1 follows argument 2.
There is no guarantee of any sort that the value returned will be +1
or -1
at any time. Any equality test based on that assumption is faulty. It is conceivable that the 32-bit and 64-bit versions of strcmp()
return different numbers for a given string comparison, but any test that looks for +1
from strcmp()
is inherently flawed.
Your comparison code should be one of:
if (strcmp(cat, ",") > 0) // cat > ","
if (strcmp(cat, ",") == 0) // cat == ","
if (strcmp(cat, ",") >= 0) // cat >= ","
if (strcmp(cat, ",") <= 0) // cat <= ","
if (strcmp(cat, ",") < 0) // cat < ","
if (strcmp(cat, ",") != 0) // cat != ","
Note the common theme — all the tests compare with 0. You'll also see people write:
if (strcmp(cat, ",")) // != 0
if (!strcmp(cat, ",")) // == 0
Personally, I prefer the explicit comparisons with zero; I mentally translate the shorthands into the appropriate longhand (and resent being made to do so).
Note that the specification of strcmp()
says:
ISO/IEC 9899:2011 §7.24.4.2 The strcmp
function
?3 The strcmp
function returns an integer greater than, equal to, or less than zero,
accordingly as the string pointed to by s1
is greater than, equal to, or less than the string pointed to by s2
.
It says nothing about +1
or -1
; you cannot rely on the magnitude of the result, only on its signedness (or that it is zero when the strings are equal).