4 min read
The Preprocessor and Macros
Prerequisites: Pointers and arrays
Beyond #include and #define constants, the preprocessor supports
macro functions and conditional compilation:
#define SQUARE(x) ((x) * (x))
printf("%d\n", SQUARE(5)); // expands to ((5) * (5)) -> 25
#ifdef DEBUG
printf("Debug mode is on\n");
#endif
Common mistakes
- Writing
#define SQUARE(x) x * xwithout the parentheses —SQUARE(1 + 2)then expands to1 + 2 * 1 + 2, evaluating to5instead of the intended9. Always wrap both the macro body and each parameter in parentheses.