Macro problem

Can anybody explain why and how is y is being evaluated twice in the following code?


1
2
3
4
#define MAX(a, b) ((a) < (b) ? (b) : (a))
int x = 5, y = 10;
int z = MAX(x++, y++);
 


Thanks!
Macros perform text replacement. MAX(x++, y++) expands to ((x++) < (y++) ? (y++) : (x++)). In fact, using MAX with expressions with side effects (i.e. expressions that modify the contents of memory) has undefined behavior.

To avoid these problems, use actual functions. std::max in <algorithm> is a drop-in replacement for MAX that will behave nicely with side effects.
Last edited on
helios wrote:
In fact, using MAX with expressions with side effects (i.e. expressions that modify the contents of memory) has undefined behavior.

Not in this case with the ternary operator because every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression (ยง5.16/1).
Oh. Alright.
Topic archived. No new replies allowed.