liveBook · Manning

Macro expansion

As explained in Modern C, Third Edition

Macro expansion is the recursive process of replacing a macro invocation and any expandable macros in its arguments with source tokens.

Macro expansion recursively replaces a function-like macro invocation and expandable macros in its arguments with source tokens. It occurs during an early translation phase, before keywords, types, variables, or other program constructs receive their later interpretation. section 17.1

Expanding BYTECOPY

#define BYTECOPY(T, S) memcpy(&(T), &(S), MINSIZE(T, S)) For BYTECOPY(A, B), each argument is expanded first. If A expands to redA and MINSIZE expands to a size comparison, the result becomes memcpy(&(redA), &(B), (sizeof((redA))<sizeof((B)) ? sizeof((redA)) : sizeof((B)))). The resulting replacement text is scanned again for further macro replacement. section 17.1

Expansion follows a fixed replacement sequence:

  • Temporarily disable the invoked macro, preventing infinite self-recursion. section 17.1
  • Parse parentheses and commas to identify arguments, requiring the argument count to match the parameters. section 17.1
  • Recursively expand macros in each argument, substitute the resulting fragments into a copy of the replacement text, and rescan it. section 17.1
  • Use an additional macro layer when an argument must expand before stringification: STRGY(__LINE__) first expands __LINE__, then STRINGIFY turns the result into a string. section 17.3
#define BYTECOPY(T, S) memcpy(&(T), &(S), MINSIZE(T, S))

Inspect the compact BYTECOPY definition that demonstrates parameter substitution and recursive expansion. section 17.1

 #define STRINGIFY(X) #X

Compare direct stringification with the two-stage expansion pattern shown by STRINGIFY and STRGY. section 17.3

How Modern C, Third Edition covers it

How deep it goes
Explains argument parsing, recursive substitution, rescanning, recursion prevention, and early translation-phase timing.
Examples
Uses BYTECOPY expansion, nested STRINGIFY and STRGY definitions, __LINE__, and trace output.
What you can do after
Evaluate macro invocations by tracing argument expansion, parameter substitution, rescanning, and stringification order.
How it connects
Connects function-like macros with preprocessing, stringification, token concatenation, and translation phases.

Also explained in

Compare how 4 books explain macro expansion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.