关于退货声明的困惑

e
int demo()
{
   static int i = 1;
   return i++;
}

int main()
{
    printf("%d %d %d\n", demo(), demo(), demo());
    return 0;
}  

输出:-

3 2 1

在第一个demo通话中,1被返回。

我听说return执行语句,控制权会传递给calling函数,而不会在called函数中进一步执行任何代码

所以我的问题是,在我的代码1中第一次调用返回时,为什么其值增加?

换句话说,我想知道返回后1为什么++执行?

马可·A

这里要记住三点:

  1. static 首次创建变量时,函数中的变量会在程序的整个过程中持续存在

  2. 返回的变量还具有postfix ++运算符,其含义是:“使用该值(即,将其返回)并在AFTERWARDS之后递增”:未返回递增的值。

这就是为什么该变量具有发生的事情的“记忆”并被增加。

->为什么您看到的是“ 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)代替用于参数传递的堆栈。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章