Vinod Ankith Devanaboina Vinod Ankith Devanaboina - 1 year ago 104
C++ Question

What is double evaluation and why should it be avoided?

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 its bad.

P.S. - Surprisingly i couldn't find any detailed explanation when googling for it except for an example in clojure (which I cant understand)

Answer Source

Imagine you wrote this:

#define Max(a,b) (a < b ? b : a)

int k = 0;
int g(){ return ++k; }

then called it like this:

auto var = Max(g(), g());

Do you know that var will be 3? This is because that Macro will simply be replaced with its proceeding definition.

auto var = (g() < g() ? g() : g());

See it Live On Coliru

As you can see that expression will be evaluated more times than you want, because unlike function calls that will be evaluated on site and the results passed as parameters, That MACRO will simply repeat such function call as the macro parameter is used in the MACRO's definition.

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, meanwhile it can be effectively done using a function templates

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download