Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
What problems might the following macro bring to the application?
I wrote a sample application with macro expansion for implementing it in my iOS (Objective C code).
It is something like:
#define SQUARE(x) ( x * x )
main( )
{
int i = 3, j, k ;
j = SQUARE( i++ ) ;
k = SQUARE( ++i ) ;
printf ( "\nValue of i++ = %d\nValue of ++i = %d", j, k ) ;
}
The output was:
Value of i++ = 9
Value of ++i = 49
Expected output was:
Value of i++ = 9
Value of ++i = 25
I’m surprised by this result. I’m little bit confused with this macro expansion.
Why did it happen? Please help me to find the reason.
This is really undefined behavior (and should not be relied on on another compiler or even the next run of the same compiler) since it increases the same variable twice in the same statement without a sequence point, but this is what seems to happen in this case;
will expand to
As this is undefined behaviour, the compiler is free to do whatever it wants (old versions of gcc made the program launch nethack ;-). To be more precise: The compiler is free to assume undefined behaviour won’t ever be called upon, and just make sure the code works correctly in “normal” cases. What happens in unexpected cases is anybody’s bet.