Macros: tokens, arguments, and pitfalls
Follow replacement tokens, grouping, repeated evaluation, stringizing, token pasting, and C23 variadic distinctions.
In this chapter9 sections
A macro replaces preprocessing tokens. It can resemble a function call without following function-call rules. We will check grouping, repeated evaluation, and the cases where a typed function gives a clearer interface.
1. A definition supplies replacement tokens
An object-like macro replaces a matching identifier, such as #define CODEDILE_LIMIT 7. A function-like macro has parameters and is invoked when its name is followed by ( as the next preprocessing token. In its definition, no whitespace may separate the macro name and the opening parenthesis. Macros do not have C block scope: a definition lasts from its directive until #undef or the end of that preprocessing translation unit.
Replacement is token-based. A macro named LIMIT does not replace part of LIMITED, or characters inside "LIMIT". Arguments normally undergo macro expansion before substitution, with special rules for # and ##; the replacement is rescanned for more macro invocations. A macro is prevented from endlessly expanding itself during its own replacement. These rules are more precise than “find and replace every matching piece of text.”
2. Preserve grouping, then examine evaluation
#define CODEDILE_SQUARE(x) ((x) * (x))
int result = CODEDILE_SQUARE(1 + 2);
Parenthesizing each expression parameter and the overall expression protects this use from precedence surprises. Without those parentheses, 1 + 2 * 1 + 2 means five. Parentheses do not fix repeated evaluation: CODEDILE_SQUARE(i++) would expand into two unsequenced modifications of i, causing undefined behavior in C17. Do not run it to discover an “expected output.”
#include <assert.h>
static inline int square_small(int value)
{
return value * value;
}
int main(void)
{
int next = 3;
int result = square_small(next++);
assert(next == 4);
assert(result == 9);
return 0;
}
This function evaluates the caller’s single argument expression once. Its contract here is deliberately small: the supplied value must have a square representable as int; the function does not make signed overflow safe. Different function arguments still have unspecified evaluation order in C17. inline does not force machine-code substitution, and static gives this file-scope function internal linkage.
3. A statement macro should act like one statement
#include <assert.h>
#define CODEDILE_SET_ZERO(target) do { (target) = 0; } while (0)
int main(void)
{
int value = 7;
if (value > 0)
CODEDILE_SET_ZERO(value);
else
value = 1;
assert(value == 0);
return 0;
}
The do { ... } while (0) wrapper accepts the caller’s normal semicolon and keeps an else attached to its intended if. The wrapper does not add a function-style parameter-type interface; the expanded code still undergoes ordinary C type checking. It also does not remove name collisions or repair repeated side effects. A break inside such a wrapper exits its own loop; it does not automatically break an outer loop. Prefer a function when a statement macro has no clear translation-time purpose.
4. Stringize spellings and form tokens deliberately
#include <assert.h>
#include <string.h>
#define CODEDILE_LIMIT 7
#define CODEDILE_RAW_STRING(x) #x
#define CODEDILE_STRING(x) CODEDILE_RAW_STRING(x)
int main(void)
{
assert(strcmp(CODEDILE_RAW_STRING(CODEDILE_LIMIT), "CODEDILE_LIMIT") == 0);
assert(strcmp(CODEDILE_STRING(CODEDILE_LIMIT), "7") == 0);
return 0;
}
The stringizing operator # uses the unexpanded argument’s spelling, with specified whitespace and escaping rules. The extra wrapper permits expansion before the inner macro stringizes. The example compares the resulting strings; it does not evaluate an expression written inside the argument.
#define CODEDILE_JOIN_RAW(a, b) a ## b
#define CODEDILE_JOIN(a, b) CODEDILE_JOIN_RAW(a, b)
#define CODEDILE_ID 7
int item7 = 42;
int value = CODEDILE_JOIN(item, CODEDILE_ID);
Token pasting with ## forms a single preprocessing token from adjacent pieces. A wrapper again permits expansion before pasting. The result must be a valid preprocessing token; this is not general string concatenation. Macro arguments are separated by top-level commas, with nested parentheses protecting commas; braces alone do not provide that protection.
5. Keep variadic and version rules visible
#include <stdio.h>
#define CODEDILE_LOG(...) printf(__VA_ARGS__)
int main(void)
{
CODEDILE_LOG("ready\n");
CODEDILE_LOG("count=%d\n", 2);
return 0;
}
C99 introduced variadic macros. This C17 form places the entire nonempty argument list in __VA_ARGS__, so both shown calls work. A different form with a named fmt parameter and printf(fmt, __VA_ARGS__) needs suitable additional arguments in C17; an omitted tail is not a portable comma-removal trick. A logging macro still inherits printf’s format and argument contracts.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.10.3, 6.5p2, 6.7.4. Stable core rules used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 6.10.4. C23 notes are separate from C17 example checks.
- GCC CPP: macro pitfalls
Macro expansion happens before expression evaluation
Explore the visual model
VISUAL MODEL
Follow the argument tokens into two replacement lists. Then evaluate the resulting C expression using its grouping.
These examples use only the side-effect-free int expressions 3 and 2 + 1. The macro definition precedes the fragment inside a function.
#define SQUARE(x) ((x) * (x))int value = SQUARE(2 + 1);
argument2 + 1Preprocessing tokensreplacement—Not available yetvalue—Not available yetRead the replacement list. Its two occurrences of x will each receive the argument’s tokens. No parameter object is created.
Parentheses repair this grouping problem; they do not make a repeated argument evaluate just once. A macro is not a function call. This model never runs SQUARE(i++) or other unsequenced modifications.
Read the complete trace
- Read the replacement list. Its two occurrences of x will each receive the argument’s tokens. No parameter object is created.
- Substitute 2 + 1 for each x. The resulting expression is ((2 + 1) * (2 + 1)). This is preprocessing, not execution of multiplication.
- At execution, the resulting expression produces 9. Parentheses decide the grouping; they do not add a function-call boundary.
Before you move on
- Macros replace preprocessing tokens rather than receiving typed argument values like functions.
- Parentheses can repair grouping without preventing repeated evaluation.
- Stringizing, token pasting, and conditional forms require their specific preprocessing rules.
Keep these ideas separate
- Grouped argument / Single evaluation
- An argument surrounded by parentheses can still be expanded more than once in a macro replacement.
Why might a small typed function be a clearer choice than a function-like macro with a side-effecting argument?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Macro arguments are always evaluated exactly once.
Token substitution does not provide a function-call-style single evaluation guarantee.
- Expansion can evaluate that expression more than once, with sequencing concerns.
✓ Correct reasoning. Inspect the replacement tokens and sequencing; do not invent an output for an invalid expansion.
- Parentheses automatically remove every repeated side effect.
Parentheses can improve grouping without removing duplicated evaluations.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded explanation is above; documented corrections are recorded in the source review.
Macro replacement operates on preprocessing tokens before ordinary C semantic analysis. It does not perform function-style type checking or obey C block scope. A macro definition applies from its definition until a corresponding #undef or the end of that preprocessing translation unit; it is not automatically active in other separately compiled files.
Object-like vs. Function-like Macros
- Object-like macros associate a name with a replacement list of preprocessing tokens, which may be empty:
#define PI 3.14159. - Function-like macros accept preprocessing-token arguments and substitute a replacement list, which need not be an expression:
#define SQUARE(x) ((x) * (x)).
Common Pitfalls
- Missing parentheses.
#define SQUARE(x) x * xlooks harmless, butSQUARE(1 + 2)expands to1 + 2 * 1 + 2, which evaluates to 5, not 9. For this expression macro, parenthesize each substituted operand and the complete expression:#define SQUARE(x) ((x) * (x)). - Multiple evaluation of side effects. Because a macro parameter is substituted everywhere it appears in the body,
SQUARE(i++)expands to((i++) * (i++)), incrementingitwice in one expression and triggering undefined behavior. A real function, by contrast, evaluatesi++exactly once before the call. - Multi-statement macros in single-line contexts. A macro such as
#define SWAP(a,b) t=a; a=b; b=t;breaks when used as the body of a brace-lessif, since only the first statement is captured by the conditional. The standard fix wraps the body indo { ... } while (0), which behaves as a single statement while still allowing a normal trailing semicolon at the call site. - One preprocessing namespace, without C block scope. Macros are not scoped like variables or functions; a macro named
MAXdefined in one header can silently collide with an identically named variable, function, or macro defined elsewhere, because replacement matches identifier preprocessing tokens; a function-like macro expands only when the next preprocessing token is(. Names inside string or character literals are not replaced.
Special Preprocessor Operators
- The stringizing operator
#turns an argument's token spelling into a string literal:#define STR(x) #xmakesSTR(hello)become"hello". Arguments used with#are not macro-expanded first; a second wrapper macro is needed when expansion before stringizing is intended. - The token-pasting operator
##joins adjacent preprocessing tokens:#define CONCAT(a,b) a##bmakesCONCAT(foo, bar)becomefoobar. The result must be a valid preprocessing token; adjacent arguments are not expanded before pasting without another macro layer. - Variadic macros (C99) use
...and__VA_ARGS__. For example,#define LOG(...) printf(__VA_ARGS__)accepts bothLOG("ready\n")andLOG("x=%d\n", x). The form#define LOG(fmt, ...) printf(fmt, __VA_ARGS__)requires a suitable nonempty variadic argument in C17 to avoid an invalid trailing comma. C23 adds__VA_OPT__for conditional token insertion.__VA_ARGS__and__VA_OPT__are preprocessing facilities, not additional language keywords.
Macros vs. Inline Functions
Prefer a static inline function when a normal typed function can express the operation. Each supplied argument expression is evaluated once, although the order of different argument evaluations is still unspecified in C17. Parameter uses inside the function do not re-evaluate caller expressions. Inlining is not guaranteed, and optimization can affect debugger visibility. Macros remain useful for token manipulation and some generic interfaces.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.