Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
My code is as follows:
#include <stdio.h>
int main()
{
int x = 10, y = 0;
x = x++;
printf("x: %d\n", x);
y = x++;
printf("y: %d\n", y);
}
Given the nature of post-increment, I would expect the following output:
x: 10
y: 10
My reasoning is that in line 5, x
should be assigned to its initial value after the increment takes place.
Instead, however, I get this:
x: 11
y: 11
Digging into the assembly, this looks like a deliberate choice to me:
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
What's going on here? Is GCC trying to save me from myself? I don't have a language reference handy but I would have thought that this breaks the intended semantics.