c32bit-64bitstrcmp

strcmp behaviour in 32-bit and 64-bit systems


The following piece of code behaves differently in 32-bit and 64-bit operating systems.

char *cat = "v,a";
if (strcmp(cat, ",") == 1)
    ...

The above condition is true in 32-bit but false in 64-bit. I wonder why this is different? Both 32-bit and 64-bit OS are Linux (Fedora).


Solution

  • 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).