I am learning C programming. And this was a question I faced very recently in an examination.
Can someone tell me why the output of the following program doesn't adhere to my reasoning(which I have explained in a concise and lucid manner below).
#include<stdio.h>
#define PRODUCT(x) ( x * x )
main( )
{
int i = 3, j, k ;
j = PRODUCT( i++ ) ;
k = PRODUCT ( ++i ) ;
printf ( "\n%d %d", j, k ) ;
}
Expected Output: 12 42 The Real Output: 12 49 .
My Reasoning for 'The Expected Output':
The PRODUCT (i++) gets replaced with the following: ( i++ * i++) which (since "i++" is a posterior operator) essentially is mathematically equivalent to ((i)*(i+1)) . And so j = 3 * 4.
At the end of this assignment to j, the value of 'i' is 5. Since in (i++ * i++) the first i++ incremented i once and then again for the next i++ after the '*' symbol. Hope you are with me. So after two increments, i now equals 5. Lets move further.
In the assignment statement for k, the PRODUCT (++i) gets replaced with (++i * ++i) which being a pre-increment operator is the mathematical equivalent of ( (i+1) * ((i+1)+1 ) ). And since i equals 5 until before this statement, the value assigned to variable 'k' should be ((5+1)((5+1)+1)) which is (67)=42 AND NOT "49"-which is the output I got. Any reasoning other than undefined behavior will be much appreciated.