When I run the following code, the return value is 11, but I was expecting it to return 25. Can someone explain this?
#include<stdio.h>
#define SQR(a) a*a
int main()
{
int i=3;
printf("%d",SQR(i+2));
return 1;
}
When I run the following code, the return value is 11, but I was expecting it to return 25. Can someone explain this?
#include<stdio.h>
#define SQR(a) a*a
int main()
{
int i=3;
printf("%d",SQR(i+2));
return 1;
}
Needs more parentheses. This:
#define SQR(a) a*a
expands to this:
i+2*i+2
which is:
3+2*3+2
which is 11 because *
has precedence over +
.
You need to define your macro like this:
#define SQR(a) ((a)*(a))
to ensure that this kind of thing doesn't happen.
Macros are not the same as regular functions.
During the reprocessing all macros are replaced exactly by what they are define. In your case, the line:
printf("%d",SQR(i+2));
is replaced by the line:
printf("%d", i+2*i+2);
So, you see the unexpected result there.
The correct way is:
#define SQR(a) ((a)*(a))
The preprocessor result will be:
printf("%d", ((i+2)*(i+2)));
Try to learn on this mistake. Issues of this kind are quite hard to debug.