#include<stdio.h>
#define sqr(n) (n*n);
int main()
{
int x =3,b;
b=sqr(x+1);
printf("%d\n", b);
return 0;
}
//the output should be 16 but my on compiling in GCC compiler the output is coming 7.can anyone explain me the reason
This line is problematic:
#define sqr(n) (n*n);
Because there's no parentheses around n
, n+1
evaluates to (n + 1 * n + 1).
The output is seven because sqr(3+1) evaluates to (3 + 1 * 3 + 1) = 7.
To fix, add parentheses:
#define sqr(n) ((n)*(n));
Then sqr(3+1) evaluates to ((3 + 1) * (3 + 1)) = 16.