这里要记住三点:
static 函数中的变量在第一次创建后会在程序的整个持续时间内持续存在
返回的变量也有 后缀 ++ 运算符,意思是:“使用该值(即返回它)并在之后增加它”:不返回增加的值。
这就是为什么该变量对所发生的事情具有“记忆”并不断增加的原因。
-> 为什么你看到的是“3 2 1”而不是“1 2 3”?
评估参数的顺序“先验”未知,由编译器决定,请参阅https://stackoverflow.com/a/12960263/1938163
如果您真的想知道值是如何先返回然后递增的,请查看生成的 asm 代码:
demo(): # @demo()
movl demo()::i, %eax # move i and put it into eax
movl %eax, %ecx # Move eax into ecx -> eax will be used/returned!
addl $1, %ecx # Increment ecx
movl %ecx, demo()::i # save ecx into i -> this is for the next round!
ret # returns!
main: # @main
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movl $0, -4(%rbp)
callq demo() # Call demo()
movl %eax, -8(%rbp) # save eax in rbp-8 (contains 1, demo::i is 2 for the next round)
callq demo() # Call demo()
movl %eax, -12(%rbp) # save eax in rbp-12 (contains 2, demo::i is 3 for the next round)
callq demo() # Call demo()
leaq .L.str, %rdi # load str address
movl -8(%rbp), %esi # esi points to 1
movl -12(%rbp), %edx # edx points to 2
movl %eax, %ecx # move eax (3) into ecx (demo::i is 4 but doesn't get used)
movb $0, %al # needed by the ABI to call printf
callq printf # call printf() and display 3 2 1
movl $0, %ecx
movl %eax, -16(%rbp)
movl %ecx, %eax
addq $16, %rsp
popq %rbp
ret
demo()::i:
.L.str:
.asciz "%d %d %d\n"
64 位 ABI 使用寄存器(RDI、RSI、RDX、RCX、R8 和 R9)而不是堆栈来传递参数。