strcmp() 为相同的字符串比较返回不同的值 [英] strcmp() return different values for same string comparisons

查看:63
本文介绍了strcmp() 为相同的字符串比较返回不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么strcmp收到相同的参数时返回不同的值?

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

这些值仍然合法,因为 strcmp 的手册页说 strcmp 的返回值可以小于、大于或等于 0,但我不明白为什么在这个例子中它们不同.

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.

推荐答案

我假设你在编译这个时使用了 GCC,我在 4.8.4 上试过了.这里的技巧是 GCC 理解某些标准库函数的语义(strcmp 就是其中之一).在您的情况下,编译器将完全消除第二个 strcmp 调用,因为它知道 strcmp 给定字符串常量 "0""9" 将是负数,并且将使用标准兼容值 (-1) 而不是进行调用.它不能对第一次调用做同样的事情,因为 s1s2 可能已经在内存中改变了(想象一个中断,或多个线程等).

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

您可以做一个实验来验证这一点.将 const 限定符添加到数组中,让 GCC 知道它们不能更改:

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

您还可以查看编译器的汇编输出(使用 -S 标志).

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

不过,最好的检查方法是使用 -fno-builtin,它会禁用此优化.使用此选项,您的原始代码在两种情况下都会打印 -9

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

这篇关于strcmp() 为相同的字符串比较返回不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆