c - strcmp 输出之谜 - strcmp 实际上是如何比较字符串的?

标签 c string strcmp

我想知道如果在同一个函数中多次使用 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/

相关文章:

python字符串拆分

java - 分割字符串时是否有替代 String[] 的方法?

c - 为什么 strcmp 的返回不同?

c - 解决使用C的strcmp函数比较两个不同结构的元素时的警告

c - 如何检查文本文件中的文本然后存储变量?

ios - Cocos2d v3 : What do you pass into drawPolyWithVerts?

c - 使 R 函数识别同一包中的 C 函数?

string - 检查字符串是否以 Rust 中的给定后缀结尾

php - 将 SQL 数据库中的字符串与 "normal"字符串进行比较

c - 指向函数实用程序的指针