YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Building programsChapter 40 of 73

Macros: tokens, arguments, and pitfalls

Follow replacement tokens, grouping, repeated evaluation, stringizing, token pasting, and C23 variadic distinctions.

7 min readIntermediateC17 baseline
Offline reading
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

C17 · illustrative fragment
#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.”

Complete C17 program
#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

Complete C17 program
#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

Complete C17 program
#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.

C17 · illustrative fragment
#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

Complete C17 program
#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

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.

  1. #define SQUARE(x) ((x) * (x))
  2. int value = SQUARE(2 + 1);
Argument tokensargument2 + 1Preprocessing tokens
Expanded expressionreplacement—Not available yet
intvalue—Not available yet

Read 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
  1. Read the replacement list. Its two occurrences of x will each receive the argument’s tokens. No parameter object is created.
  2. Substitute 2 + 1 for each x. The resulting expression is ((2 + 1) * (2 + 1)). This is preprocessing, not execution of multiplication.
  3. 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.
Explain it in your own words

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.

A macro uses its parameter twice. Why can a side-effecting argument be risky?
Read the explanation for every choice
  1. Macro arguments are always evaluated exactly once.

    Token substitution does not provide a function-call-style single evaluation guarantee.

  2. 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.

  3. 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

  1. Missing parentheses. #define SQUARE(x) x * x looks harmless, but SQUARE(1 + 2) expands to 1 + 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)).
  2. Multiple evaluation of side effects. Because a macro parameter is substituted everywhere it appears in the body, SQUARE(i++) expands to ((i++) * (i++)), incrementing i twice in one expression and triggering undefined behavior. A real function, by contrast, evaluates i++ exactly once before the call.
  3. 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-less if, since only the first statement is captured by the conditional. The standard fix wraps the body in do { ... } while (0), which behaves as a single statement while still allowing a normal trailing semicolon at the call site.
  4. One preprocessing namespace, without C block scope. Macros are not scoped like variables or functions; a macro named MAX defined 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) #x makes STR(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##b makes CONCAT(foo, bar) become foobar. 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 both LOG("ready\n") and LOG("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.

CHAPTER 40 / 73

In this chapter

Macros: tokens, arguments, and pitfalls

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping