增量后运算符:意外行为

dan*_*ben 8 c gcc post-increment

可能重复:
任何人都可以解释这些未定义的行为(i = i ++ + ++ i,i = i ++等...)

我的代码如下:

#include <stdio.h>
int main()
{
  int x = 10, y = 0;
  x = x++;
  printf("x: %d\n", x);
  y = x++;
  printf("y: %d\n", y);
}
Run Code Online (Sandbox Code Playgroud)

考虑到后增量的性质,我希望得到以下结果:

x: 10
y: 10
Run Code Online (Sandbox Code Playgroud)

我的理由是,在第5行,x应该在增量发生后分配给它的初始值.

相反,我得到了这个:

x: 11
y: 11
Run Code Online (Sandbox Code Playgroud)

深入到装配中,这对我来说是一个刻意的选择:

LCFI2:
        movl    $10, -4(%rbp)   // this is x
        movl    $0, -8(%rbp)    // this is y
        incl    -4(%rbp)        // x is simply incremented
        movl    -4(%rbp), %esi
        leaq    LC0(%rip), %rdi
        movl    $0, %eax
        call    _printf
        movl    -4(%rbp), %eax  // now x is saved in a register,
        movl    %eax, -8(%rbp)  // copied to y,
        incl    -4(%rbp)        // and finally incremented
        movl    -8(%rbp), %esi
        leaq    LC1(%rip), %rdi
        movl    $0, %eax
        call    _printf
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?海湾合作委员会试图拯救我自己吗?我没有方便的语言参考,但我认为这打破了预期的语义.

Geo*_*che 13

行为未定义,因为没有插入序列点x = x++,请参阅例如C FAQ.