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.
++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand. a++ returns the value of a before incrementing. It is a post-increment operator since ++ comes after the operand.
2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;
The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one. if the expression is a = b++; and b is holding 5 at first, then a will also hold 5.
The decrement (–) and increment (++) operators are special types of operators used in programming languages to decrement and increment the value of the given variable by 1 (one), respectively.
The behaviour is undefined as there is no intervening sequence point in x = x++
, see e.g. the C FAQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With