请注意,我已经检查了与该标题相关的问题,但从我的角度来看,它们与该问题无关。
最初,我认为program1和program2会给我相同的结果。
//Program 1
char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));
//Output: -4
//Program 2
printf("%d", strcmp("abcd", "efgh"));
//Output: -1
我可以发现的唯一区别是在program2中我传递了字符串文字,而在程序中我传递char *
了strcmp()
函数的参数。
为什么这些看似相同的程序的行为之间存在差异?
平台:Linux Mint编译器:g ++
编辑:实际上,program1总是打印第一个不匹配字符的ascii码的差,但是,如果string2中第一个不匹配字符的ascii码大于string1的字符,则program2打印-1。
这是您的C代码:
int x1()
{
char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));
}
int x2()
{
printf("%d", strcmp("abcd", "efgh"));
}
这是两个函数生成的程序集输出:
.LC0:
.string "abcd"
.LC1:
.string "efgh"
.LC2:
.string "%d"
x1:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], OFFSET FLAT:.LC0
mov QWORD PTR [rbp-16], OFFSET FLAT:.LC1
mov rdx, QWORD PTR [rbp-16]
mov rax, QWORD PTR [rbp-8]
mov rsi, rdx
mov rdi, rax
call strcmp // the strcmp function is actually called
mov esi, eax
mov edi, OFFSET FLAT:.LC2
mov eax, 0
call printf
nop
leave
ret
x2:
push rbp
mov rbp, rsp
mov esi, -1 // strcmp is never called, the compiler
// knows what the result will be and it just
// uses -1
mov edi, OFFSET FLAT:.LC2
mov eax, 0
call printf
nop
pop rbp
ret
当编译器看到strcmp("abcd", "efgh")
它时,"abcd"
便会事先知道结果,因为它知道早于"efgh"
。
但是,如果看到strcmp(a,b)
它,则不知道,因此会生成实际调用的代码strcmp
。
对于其他编译器或不同的编译器设置,情况可能会有所不同。您真的不应该至少在初学者的级别上关心这些细节。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句