#include<stdio.h>
#define sqr(i) i*i
int main()
{
printf("%d %d", sqr(3), sqr(3+1)); //output 9,7
return 0;`
}
why the out put is 9,7? can anybody explain with steps how that 7 is getting evaluated
#include<stdio.h>
#define sqr(i) i*i
int main()
{
printf("%d %d", sqr(3), sqr(3+1)); //output 9,7
return 0;`
}
why the out put is 9,7? can anybody explain with steps how that 7 is getting evaluated
The macro sqr(i) i*i
for sqr(3+1)
will be evaluated to 3+1*3+1
which is ... 7
. Put the arguments of the macro in parentheses:
#define sqr(i) (i) * (i)
if you really want to use a macro for this.
You are using the macro you define but the definition is a pitfall itself:
#define sqr(i) i*i
when you do this sqr(3) then this will be replaced and executed as 3*3 resulting 9
BUT HERE IS THE PROBLEM
sqr(3+1) will be replaced and executed as 3+1*3+1 resulting 3+3+1 =7
because the parameter will not be resolved before is passed to the macro...
instead it will just make a dumb-replace, changing every coincidence of i for the parameter 3+1
your macro behaves
input output
3 9
3+1 7
4 16