Strcmp () returns different values ​​for identical 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 does strcmp return different values ​​when it receives the same parameters?

These values ​​are still legal, as the strcmp man page states that the return value of strcmp may be less than, greater than, or equal to 0, but I don’t understand why they differ in this example.

+8
string-comparison strcmp man
source share
2 answers

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

You can do an experiment to test this. Add the const qualifier to the arrays so that GCC knows 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 compiler output collector (use the -S flag).

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

+4
source share

The difference is with strcmp implementation. As long as it matches (<0, 0,> 0), it should not matter to the developer. You cannot rely on anything else. As far as you know, the source code can determine that it should be negative, and randomly generate a negative number to drop you.

+3
source share

All Articles