Imagine you wrote this:
#define Max(a,b) (a < b ? b : a)
int x(){ turnLeft(); return 0; }
int y(){ turnRight(); return 1; }
then called it like this:
auto var = Max(x(), y());
Do you know that turnRight()
will be executed twice? That macro, Max
will expand to:
auto var = (x() < y() ? y() : x());
After evaluating the condition x() < y()
, the program then takes the required branch between y() : x()
: in our case true
, which calls y()
for the second time. See it Live On Coliru.
Simply put, passing an expression as an argument to your function-like macro, Max
will potentially evaluate that expression twice, because the expression will be repeated where ever the macro parameter it takes on, is used in the macro's definition. Remember, macros are handled by the preprocessor.
So, bottom line is, do not use macros to define a function (actually an expression in this case) simply because you want it to be generic, while it can be effectively done using a function templates
PS: C++ has a std::max
template function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…