This programm returns a=25, but if I define the sqr(x) as (x*x) it returns a=11. Why does this happen?
#include <stdio.h>
#define sqr(x) ((x)*(x))
main (){
int a,b=3;
a=sqr(b+2);
printf("a=%d\n",a);
return 0;
}
This programm returns a=25, but if I define the sqr(x) as (x*x) it returns a=11. Why does this happen?
#include <stdio.h>
#define sqr(x) ((x)*(x))
main (){
int a,b=3;
a=sqr(b+2);
printf("a=%d\n",a);
return 0;
}
The difference is in the way the macro is expanded.
With the extra parenthesis, the preprocessor expands the expression sqr(b+2)
to this:
((b+2)*(b+2))
Which the compiler then interprets as:
a = ((3+2)*(3+2))
= (5*5)
= 25
Without the extra parenthesis, the preprocessor expands the expression sqr(b+2)
to this:
(b+2*b+2)
Which the compiler interprets as:
a = (3+2*3+2)
= (3+(2*3)+2)
= (3+6+2)
= 11
The *
(multiplication) operator has a higher precedence than the +
(addition) operator.
If the macro is defined like
#define sqr(x) ( x * x )
when in this macro extension
sqr(b+2);
after substituting x
for b + 2
you will have
b + 2 * b + 2
It is not the same as
( b + 2 ) * ( b + 2 )
that you would have if the macro was defined like
#define sqr(x) ( ( x ) * ( x ) )