Search code examples
string-comparisonstrcmpmanpagestring.h

strcmp() return different values for same string comparisons


char s1[] = "0";
char s2[] = "9";
printf("%d\n", strcmp(s1, s2));   // Prints -9
printf("%d\n", strcmp("0", "9")); // Prints -1

Why do strcmp returns different values when it receives the same parameters ?

Those values are still legal since strcmp's man page says that the return value of strcmp can be less, greater or equal than 0, but I don't understand why they are different in this example.


Solution

  • I assume you are using GCC when compiling this, I tried it on 4.8.4. The trick here is that GCC understands the semantics of certain standard library functions (strcmp being one of them). In your case, the compiler will completely eliminate the second strcmp call, because it knows that the result of strcmpgiven string constants "0" and "9" will be negative, and a standard compatible value (-1) will be used instead of doing the call. It cannot do the same with the first call, because s1 and s2 might have been changed in memory (imagine an interrupt, or multiple threads, etc.).

    You can do an experiment to validate this. Add the const qualifier to the arrays to let GCC know that they cannot be changed:

    const char s1[] = "0";
    const char s2[] = "9";
    printf("%d\n", strcmp(s1, s2));   // Now this will print -1 as well
    printf("%d\n", strcmp("0", "9")); // Prints -1
    

    You can also look at the assembler output form the compiler (use the -S flag).

    The best way to check however is to use -fno-builtin, which disables this optimization. With this option, your original code will print -9 in both cases