C/C++ Arena

Step 2 of 5

Macro pitfalls

Macros can take arguments, but they're pure text replacement, which bites:

#define SQUARE(x) x * x
SQUARE(1 + 2)   // becomes 1 + 2 * 1 + 2 = 5, not 9!

The fix: wrap every argument and the whole body in parentheses:

#define SQUARE(x) ((x) * (x))

Your turn: DOUBLE(3 + 4) * 2 should be 28, but this prints 18. Fix the DOUBLE macro.

Previous: #define constants Next: Bitwise operators