Reputation: 101
-- Hello, I can`t understand why "#define max(a,b) (a>b)?(a):(b)" does not work that i expected.
#include<cstdio>
#define max(a,b) (a>b)?(a):(b)
int main(void){
printf("%d\n",max(3,5)); // result = 5 (work correctly)
int a = 3 + max(3,5);
printf("%d\n",a); // result = 3 (work incorrect and i don`t know why..)
}
i can`t why variable + macro does not work.
but, In this case "#define max(a,b) ((a>b)?(a):(b))" work correctly. even that var + macro situation.
plz anybody clarify this.. thx.
Upvotes: 1
Views: 63
Reputation: 311606
When you have this:
#define max(a,b) (a>b)?(a):(b)
And you write this:
int a = 3 + max(3,5);
That expands to:
int a = 3 + (a>b)?(3):(5)
Because +
has a higher operator precendence than ?
, this is effectively:
int a = (3 + (a>b)) ? (3) : (5)
And since 3 + (a>b)
is always going to evaluate to a true-ish value, the result will always be 3
.
By putting the whole expansion in parentheses:
#define max(a,b) ((a>b)?(a):(b))
You get instead:
int a = 3 + ((a>b)?(3):(5))
Because the outer parentheses group the ternary operator expression, you get the result you expect.
Note that as @zwol writes in a comment, you should actually write your macro like:
#define max(a,b) (((a)>(b))?(a):(b))
The extra parentheses around a
and b
in (a)>(b)
protect against exactly this sort of operator precedence problem.
Upvotes: 6
Reputation: 201447
Operator precedence. I get a warning with clang
.
test.cc:7:15: warning: operator '?:' has lower precedence than '+'; '+' will be evaluated first [-Wparentheses] int a = 3 + max(3,5);
Easy to fix with parenthesis.
#define max(a,b) ((a>b)?(a):(b))
Upvotes: 2