Possible Duplicate:
Undefined Behavior and Sequence Points
pre fix and post fix increment in C
Please explain how this program goes on to print i=2
#include<stdio.h>
void main()
{
int i=1;
i=i+2*i--;
printf("%d",i);
}
By the logic it should evaluate the value 3 because — 1+2*1=3
But this first evaluates i– and the updates the value of i. Why is this happening? :S
Modifying a variable in an expression and then assigning that result to the same variable is undefined behavior, so any behavior you’re seeing is technically correct (including rebooting the computer, or destroying the universe). From the C standard, §6.5.2:
To fix it, move the post-decrement out of the expression, like this: