Module 15: The C Preprocessor & Macro Metaprogramming

Duration: 3.0 Hours • Compile-Time Metaprogramming
1. Macro Traps 1 / 4

Function-Like Macros & Parentheses Pitfalls

Why macros are raw text substitution, NOT real functions

macro_traps.c
// DANGEROUS MACRO (Missing parentheses):
#define BAD_SQUARE(x) x * x
// BAD_SQUARE(1 + 2) expands to: 1 + 2 * 1 + 2 = 1 + 2 + 2 = 5! (NOT 9)

// CORRECT MACRO (Fully parenthesized):
#define SAFE_SQUARE(x) ((x) * (x))
// SAFE_SQUARE(1 + 2) expands to: ((1 + 2) * (1 + 2)) = 9!

// DOUBLE-EVALUATION TRAP:
int a = 3;
int res = SAFE_SQUARE(a++); // Expands to: ((a++) * (a++)) -> a is incremented TWICE!