I have started reading Effective C++ and at some point in item 2, the following is mentioned:
// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
...
int a = 5, b = 0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once
Here, the number of times that a is incremented before calling f depends on what it is being compared with!
Indeed, if I use a simple print statement in f
, 7 gets printed in the first call, but I cannot for the life of me figure out why. Am I missing something obvious?
The compiler replaces the macros with exactly what you pass in, verbatim. So you end up with
int a = 5, b = 0;
f((++a) > (b) ? (++a) : (b));
f((++a) > (b+10) ? (++a) : (b+10));