liveBook · Manning

Token concatenation

As explained in Modern C, Third Edition

The token concatenation operator ## joins two preprocessing tokens into a single preprocessing token during macro replacement.

The preprocessing operator ## joins two preprocessing tokens during macro replacement, producing one token. For example, T ## _init combines rat and _init into rat_init, or toto and _init into toto_init. section 13.4

Token concatenation is useful when macros must generate names or select among related macro definitions.

  • Builds type-specific function names such as rat_init from a type argument and a common suffix. section 13.4
  • Supports macro libraries that generate names for other macros or functions automatically. section 17.3
  • Can dispatch between macros by concatenating an identifier with either Iplus or an empty token. section 17.4.1

Generating an initializer call

The definition #define P99_NEW(T, ...) T ## _init(malloc(sizeof(T)), __VA_ARGS__) turns P99_NEW(rat, 13, 7) into rat_init(malloc(sizeof(rat)), 13, 7). The ## operation creates the function identifier; __VA_ARGS__ supplies the remaining arguments. section 13.4

#define P99_NEW(T, ...) T ## _init(malloc(sizeof(T)), __VA_ARGS__)

Inspect the complete macro definition that combines token concatenation with a variadic argument list. section 13.4

How Modern C, Third Edition covers it

How deep it goes
Explains ## through concrete expansions and dispatch, but does not develop broader preprocessing-token validity rules.
Examples
Uses P99_NEW to form rat_init and a fprintf dispatcher to form FPRINTF_IIIplus or retain FPRINTF_II.
What it assumes
Assumes familiarity with C macros and variadic arguments while defining ## through small macro expansions.
What you can do after
Apply it via C macro definitions to generate related function or macro names during preprocessing.
How it connects
Connects token concatenation with macro replacement, function-like macros, variadic macros, and preprocessing.

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.