【发布时间】:2011-03-17 17:24:52
【问题描述】:
可能重复:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
我的代码如下:
#include <stdio.h>
int main()
{
int x = 10, y = 0;
x = x++;
printf("x: %d\n", x);
y = x++;
printf("y: %d\n", y);
}
鉴于后增量的性质,我希望得到以下输出:
x: 10
y: 10
我的理由是在第 5 行中,x 应该在增量发生后分配给它的初始值。
然而,我得到了这个:
x: 11
y: 11
深入研究程序集,这对我来说似乎是一个深思熟虑的选择:
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
这里发生了什么? GCC 是想把我从自己身边救出来吗?我没有方便的语言参考,但我认为这会破坏预期的语义。
【问题讨论】:
-
在过去糟糕的日子里,
a = 1 + a在某些语言中是所有新错误都会踩到的地雷。 -
@caf - 你是对的,这是重复的(尽管不幸的是,这个问题没有提供任何有用的方法来搜索它)。
-
当你说“但是,我得到这个:x = 11, y =11”时,你使用的是什么编译器。我检查了 codeblocks 和 onlinegdb,他们都给了我 x=10 , y = 10 正如预期的那样。
标签: c gcc post-increment