preprocessor

what is the difference between:

#define getMax1(a,b) a>b?a:b

and

#define getMax2(a,b) ((a)>(b)?(a):(b))


The cout statement:
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{

int a,b;
a =12;
b =10;
cout<<getMax1(a,b);//does not work
printf("%d",getMax1(a,b));//works

cout<<getMax2(a,b);//works

return 0;
}
This is exactly why macros are evil.

Just use std::max in <algorithm>. Avoid #defining macros. They lead to all sorts of problems.


To actually answer your question... this macro:

cout<<getMax1(a,b);

gets expanded to this:

cout << a>b?a:b ; (spaced added for clarity)

Note that the the << operator has the highest precedence of all those operators, so it is evaluated first.

So it's kind of like:

(cout << a) > b?a:b;

So you end up outputting a to cout, and then trying to compare the result (cout) with b, which doesn't make any sense, which is why the compiler complains.

getMax2 doesn't have that problem because the entire macro is encased in parenthesis... so
cout<<getMax2(a,b) expands to cout << ((a)>(b)?(a):(b)) and the parenthesis ensure the > and ?: operators are evaluated first, then then the result is send to cout afterwards.
Last edited on
You should definitely avoid macros unless you really need textual replacement. Another evil thing that can happen with some macros is
1
2
3
4
cout << getMax(a,b++);

//gets expanded to
cout << (a > b++ ? a : b++);

and you'll end up incrementing b twice.
just a correction:



1
2
3
4
cout << getMax(a,b++);

//gets expanded to
cout << (a > b++ ? a : b++);



does not increment b twice. it just increments it once since its a post-increment. However, if you doa pre-increment, such as

cout<<getMax(a,++b);

then b increments by 2.
Um, actually it does. It increments b twice.
Addendum: It increments b twice if the expression ( a > b++) evaluates to false.
a strange thing appeared:

1
2
3
int x=12; 
cout << getmax(7,x++) << ":"<<x<<endl;
cout<<x<<endl;


13:12
14


why x is still printed as 12 and not the updated 13.
According to the C++ standard, it is not defined as to when x is post incremented
within that line of code. Research sequence points in C++.
Topic archived. No new replies allowed.