6.1 Macros and the Preprocessor
The preprocessor handles your source code before the real compilation starts. #define creates a macro, which is a text substitution done before compiling.
Object-like macros are often used to name constants:
#define PI 3.1415926
#define MAX_USERS 100
double area = PI * r * r;Function-like macros look like functions but are still text substitution. Wrap parameters in parentheses to avoid precedence bugs.
#define SQUARE(x) ((x) * (x))
int n = SQUARE(3 + 1); // expands to ((3 + 1) * (3 + 1)) = 16If you write #define SQUARE(x) x * x, then SQUARE(3 + 1) expands to 3 + 1 * 3 + 1, which is 7 — the classic missing-parentheses trap.
Conditional compilation includes different code depending on whether a macro is defined. It is common for debug switches or cross-platform code:
#define DEBUG 1
#if DEBUG
printf("x = %d\n", x);
#endifMacros have no type checking, so prefer const constants and real functions when you can; macros fit best for naming constants and conditional compilation.