liveBook · Manning

Textual substitution

As explained in Modern C

Textual replacement is the preprocessing technique of substituting replacement tokens for macro names and parameters without first interpreting them as C expressions or statements.

Textual substitution replaces macro names and parameters with replacement tokens during preprocessing, before the compiler interprets the result as C expressions or statements. The process follows rules specified by the C standard. section 16.1

For a function-like macro call, substitution proceeds in a defined sequence:

  • Recognize the macro name followed by parentheses and temporarily disable that macro to prevent infinite recursion. section 16.1
  • Scan the argument list, matching parentheses and using top-level commas to separate arguments. section 16.1
  • Recursively expand macros inside each argument, then replace parameter occurrences in a copy of the replacement text. section 16.1

Expanding BYTECOPY

BYTECOPY(A, B) can first expand A to redA, then substitute the resulting fragments into memcpy(&(T), &(S), MINSIZE(T, S)). The visible output is ordinary C text produced before compilation. section 16.1

memcpy(&(redA), &(B), (sizeof((redA))<sizeof((B))?sizeof((redA)):sizeof((B))
    ))


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":0,\"ch\":23},{\"line\":0,\"ch\":29}],[{\"line\":0,\"ch\":23},{\"line\":0,\"ch\":29}],[{\"line\":0,\"ch\":23},{\"line\":0,\"ch\":29}],[{\"line\":0,\"ch\":23},{\"line\":0,\"ch\":29}]]"}
!@%STYLE%@!

Compare a macro invocation with its expanded memcpy expression and observe repeated parameter replacement. section 16.1

How Modern C covers it

How deep it goes
Traces argument parsing, recursive expansion, parameter replacement, and recursion prevention, but not later compilation.
Examples
Uses BYTECOPY, MINSIZE, redA, and expanded memcpy expressions to show substitution.
What you can do after
Evaluate macro calls by tracing argument collection, recursive expansion, and replacement-text construction.
How it connects
Connects preprocessing with function-like macros, macro arguments, replacement text, and recursive expansion.

Related concepts

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