How to evaluate this statement?

c++

Solution

When you type:

ABS(2) + ABS(-3)

This will substitute out to:

2 >= 0 ? 2 : (-1) * 2 + -3 >= 0 ? -3 : (-1) * -3

You can break this down:

2 >= 0 ? 2 : -5 >= 0 ? -3 : (-1) * -3

Or:

2 >= 0 ? 2 : (-5 >= 0 ? -3 : (-1) * -3)

The first part (`2 >= 0`) evaluates as true, so it evaluates to `2`.

Note that you could easily solve this by writing the macro as:

#define ABS(X) ((X) >= 0 ? (X) : (-1) * (X))

This will keep the evaluation order as expected, and cause it to resolve to 5 instead of 2. That being said, using an inline function would be much cleaner, and avoid this entire scenario.

Problem

If I defined the absolute value of a number as ``` #define ABS(X) X >= 0 ? X : (-1) * X ``` what would ``` ABS(2) + ABS(-3) ``` evaluate to? My friend claims it evaluates to 2.

Original source