这是undefined behavior 使用返回值时你丢弃一个值返回函数的结尾,你不能依赖这个行为。
这在草案 C99 标准部分 6.9.1 函数定义第 12 段中有所涉及:
如果到达终止函数的},并且函数调用的值被
调用者,行为未定义。
与 C11 标准草案中的部分和段落相同。
在您的情况下,它只能靠运气起作用,可能返回值在您返回时不会被覆盖的寄存器中返回。对于System V calling convention 将在eax/rax 中返回一个足够小的参数,如果我们查看带有-fverbose-asm 标志的稍微修改过的测试程序live on Coliru using gcc:
#include <stdio.h>
int main()
{
int slogan( ) ;
int c = 5, d ;
c = slogan( ) ;
d = printf ( "\n%d", c ) ;
printf ( "\n%d", d ) ;
}
int slogan( )
{
printf ( "\nOnly He men use C!" ) ;
}
我们可以从程序集中看到c和d从eax获取它们的值:
movl %eax, -4(%rbp) # tmp61, c
movl -4(%rbp), %eax # c, tmp62
movl %eax, %esi # tmp62,
movl $.LC0, %edi
movl $0, %eax
call printf
movl %eax, -8(%rbp) # tmp63, d
movl -8(%rbp), %eax # d, tmp64
movl %eax, %esi # tmp64,
movl $.LC0, %edi
movl $0, %eax
call printf