What is double evaluation and why should it be avoided?

AnkithD picture AnkithD · Sep 11, 2016 · Viewed 7k times · Source

I was reading that in C++ using macros like

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

can result in a 'double evaluation'. Can someone give me an example of when a double evaluation occurs and why it's bad?

P.S.: Surprisingly I couldn't find any detailed explanation when googling for it except for an example in Clojure (which I can't understand).

Answer

WhiZTiM picture WhiZTiM · Sep 11, 2016

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.