I have noticed this strange behavior of macro functions while using pre increment operator. I know it is not preferable to use pre increment operator with macros but still I would like to know the reason behind the execution of the following 2 codes:
#include <stdio.h>
#define SQR(x) {x*x }
int main()
{
int a=4;
int b=SQR(a++);
int c=SQR(++a);
printf("%d.....%d....%d\n",b,c,a*b*c);
return 0;
}
The output of this is:
20.....64....10240
The first value b is 20, which is okay 4*5. But why the value of C is 64 i.e. 8*8 instead of 7*8?
And I just replaced the sequence of execution like this:
#include <stdio.h>
#define SQR(x) {x*x }
int main()
{
int a=4;
int c=SQR(++a);
int b=SQR(a++);
printf("%d.....%d....%d\n",b,c,a*b*c);
return 0;
}
The output of this is:
42.....36....12096
Strange isn't it? The pre increment again had some issue. It gave 42 i.e. 6*7 instead of 5*6 and after that the post increment also gave wrong answer 36 i.e. 6*6 instead of 6*7.
It would be a great help if anyone can explain why the outputs are like this?
MACROs are textual replacement, so your code
expands to something like
and,
int c=SQR(++a);
toint c = ++a*++a;
which invokes undefined behavior. To elaborate the why part for this, please refer to this well-written answer.