Reputation: 99
I have defined the following max macro
#define max(a,b)(a>b?a:b);
Inside the main() I am doing the following
int t,a,b,c,d;
t=max(a,b)+max(c,d);
But the output is not as expected.t shows only the maximum value among a and b. What could be the problem?
Upvotes: 1
Views: 85
Reputation: 1490
Remove the ;
. a #define
is just text replacement.
You should also put a
and b
in parenthesis as a best practice. This one generally won't do much, since comparison operators take precedence over probably anything you might pass in, but say it were:
#define mul(a, b) (a * b)
and then you say mul(5-3, 10+2)
From this you'd expect the output to be 24 (2 * 12), but what actually gets executed is 5-3 * 10+2
, and using order of operations, this becomes 5-(3*10)+2
, so your answer would end up as -23 instead. If it had been defined as
#define mul(a, b) ((a) * (b))
You wouldn't have this problem.
Upvotes: 2
Reputation: 95968
This will be like writing:
t = (a>b?a:b);+(a>b?a:b);
(Check the preprocessor output)
Remove the ;
from the define.
Upvotes: 5