C Reference ยท Preprocessor
Macro pitfalls
Common C macro mistakes and their fixes: missing parentheses, arguments evaluated twice, semicolon traps, do-while(0), name clashes and macros vs functions.
Macros are text substitution, and almost every macro bug comes from forgetting that. The preprocessor does not know about types, precedence or scope: it pastes tokens, and the compiler then parses the result. A macro that looks like a function call can therefore behave in surprising ways.
This page collects the traps that cause the most trouble and shows the standard defence against each. When a macro gets complicated, the best defence is often to use a static inline function or a constexpr/enum constant instead.
#define SQUARE(x) x * x /* wrong: SQUARE(1 + 2) is 1 + 2 * 1 + 2 */ #define SQUARE(x) ((x) * (x)) /* better, but still evaluates x twice */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The main traps
1. Missing parentheses
Wrap every use of a parameter in the replacement text in parentheses, and wrap the whole replacement in parentheses when it is an expression. The first guards against operator precedence in the argument (SQUARE(1 + 2)), the second against precedence in the surrounding code (100 / BAD_DOUBLE). A macro whose replacement is a statement or declaration is not wrapped this way (see below).
2. Arguments evaluated more than once
If a parameter appears twice in the replacement, the argument expression is evaluated twice. With MAX(i++, j) the increment may run twice, and with MAX(next(), 0) the function is called twice. Never pass expressions with side effects to a macro that is not documented as safe. Beware that an unsequenced double modification such as SQUARE(i++) is undefined behavior, not just a surprise.
If you can use GCC or Clang, a statement expression with typeof evaluates once (({ typeof(a) _a = (a); ... })), but it is not standard C. In C23, typeof is standard but statement expressions are not. A static inline function avoids the problem for good.
3. Statement-like macros and the trailing semicolon
A multi-statement macro pasted into if (x) MACRO(...); else ... breaks, because only its first statement belongs to the if. Wrap such macros in do { ... } while (0): it is a single statement that requires the semicolon the caller writes. Never add that final semicolon inside the macro.
4. Name collisions inside the macro
A local variable declared inside a macro (like t in the swap) can capture a variable of the same name that the caller passes in. SWAP_GOOD(t, u) would be broken by the int t inside. Use unlikely names (swap_tmp_) or avoid macro locals.
5. Commas in arguments
The preprocessor splits arguments at top-level commas. MAX(f(1, 2), 3) is fine because the commas are inside parentheses, but a compound literal or template-like initializer such as MAX((struct P){1, 2}.x, 3) can fail, because braces do not protect commas. Parenthesize the argument.
6. Macros ignore scope and type
A macro is not a scoped name: #define count 10 replaces every later count, including struct members and parameters. Give macros ALL_CAPS names so they stand out, and #undef temporary ones. A macro also has no type, so #define SIZE 10u works but cannot be seen in a debugger; prefer enum { SIZE = 10 }; or C23 constexpr int size = 10; where possible.
Usage notes
- Function-like macro name without a call.
MAXwithout parentheses is left alone, which allows a function and a macro with the same name ((MAX)(a, b)forces the function). - Stringify and paste need extra layers.
#xandx##ysuppress expansion of their operands; use a two-level helper (STR(x)callsSTR_(x)) to expand first. See the#operator. - Do not end a macro with a semicolon and do not make it span unbalanced braces.
- Macros cannot be recursive. A macro's own name is not re-expanded in its replacement.
- Debuggers and error messages show the expanded text, which makes macro mistakes hard to read; use
gcc -Eto see the preprocessed output. - Prefer alternatives:
static inlinefunctions for computations,enumorconstexprfor constants,_Genericfor type-dependent code.
Related
#define, Variadic macros, Macros vs. functions,inline- Lessons: Macros, The preprocessor