strcmp() return different values for same string comparisons

一曲冷凌霜 提交于 2019-11-28 07:30:23

问题


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.


回答1:


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




回答2:


The difference is due to the implementation of strcmp. As long as it conforms to the (<0, 0, >0), it shouldn't matter to the developer. You cannot rely on anything else. For all you know, the source code could be determining it should be negative, and randomly generating a negative number to throw you off.



来源:https://stackoverflow.com/questions/33091350/strcmp-return-different-values-for-same-string-comparisons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!