This question already has answers here:
Closed 7 years ago.
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;
#define SQUARE(x) ( x * x )
j = SQUARE( i++ ) ;
k = SQUARE( ++i ) ;
will expand to
j = (i++ * i++); // Compiler could do i * i, then increment twice, or use i * (i + 1), or...
k = (++i * ++i); // Same as above
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.
You are invoking undefined behaviour by modifying the i
more than once without an intervening sequence point.
After the marco subsitution, the two lines will look like this:
j = ( i++ * i++ ) ;
k = ( ++i * ++i ) ;
This is because you are incrementing single variable twice between two sequence points. Hence this is a undefined behaviour
int i = 3, j, k ;
j = SQUARE( i++ ) ; // it becomes (i++ * i++)
k = SQUARE( ++i ) ; // it becomes (++i * ++i)
hence the output coming is undefined.
the output that you are getting is because after first xpression i is to be incremented twice
so in secon expression where i is getting incremented twice due to pre increment it also gets incremented twice for above post increment.
j=(i++ * i++)//it comes 3*3
k=(++i * ++i)// it comes 7 as two increments of above xpression