我想知道如果在同一个函数中多次使用 strcmp()
会返回不同的值。下面是程序。第一种情况我知道它为什么打印 -6。但是在第二种情况下,为什么会打印-1呢?
#include<stdio.h>
#include<string.h>
int main()
{
char a[10] = "aa";
char b[10] = "ag";
printf("%d\n",strcmp(a, b));
printf("%d\n",strcmp("aa","ag"));
return 0;
}
它产生的输出如下
[sxxxx@bhlingxxx test]$ gcc -Wall t51.c
[sxxxx@bhlingxxx test]$ ./a.out
-6
-1
为什么第二个strcmp()
的输出是-1?在这里玩的是Compiler吗?如果是这样,它的具体优化是什么?
最佳答案
C standard关于 strcmp
的返回值,说明如下:
第 7.24.4.2p3 节:
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
因此,只要结果符合该描述,它就符合 C 标准。这意味着编译器可以执行优化以符合该定义。
如果我们看汇编代码:
.loc 1 7 0
leaq -32(%rbp), %rdx
leaq -48(%rbp), %rax
movq %rdx, %rsi
movq %rax, %rdi
call strcmp
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
.loc 1 8 0
movl $-1, %esi # result of strcmp is precomputed!
movl $.LC0, %edi
movl $0, %eax
call printf
在第一种情况下,数组被传递给 strcmp
以调用 strcmp
并生成对 printf
的调用。然而,在第二种情况下,字符串常量被传递给两者。编译器看到这一点并自行生成结果,优化对 strcmp
的实际调用,并将硬编码值 -1 传递给 printf
。
关于c - strcmp 输出之谜 - strcmp 实际上是如何比较字符串的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54710944/