Skip to main content
Macro concatenation in C is performed using the token-pasting operator (##) during the preprocessing phase. It instructs the preprocessor to merge two adjacent tokens within a macro’s replacement list into a single, unified preprocessing token before the compiler begins syntactic or semantic analysis.

Syntax

The ## operator is placed between two tokens in a macro definition:
When invoked as CONCAT(foo, bar), the preprocessor yields the single identifier token foobar.

Technical Mechanics

  1. Whitespace Elimination: The preprocessor removes all whitespace preceding and following the ## operator, fusing the left and right operands.
  2. Token Validity: The resulting concatenated sequence must form a valid C preprocessing token (e.g., an identifier, an integer constant, or a punctuator). If the fusion results in an invalid token (e.g., concatenating + and _), the behavior is undefined, and modern compilers will typically halt with an error.
  3. Placement Restrictions: The ## operator cannot appear at the absolute beginning or the absolute end of a macro replacement list.

Expansion and Evaluation Order

A critical mechanical rule of the C preprocessor is that macro arguments immediately adjacent to the ## operator are not macro-expanded prior to concatenation. The preprocessor pastes the literal tokens passed to the macro.
To force the preprocessor to expand arguments before concatenating them, you must use a two-level macro indirection. This forces the preprocessor to perform an argument prescan.

Multiple Concatenations

Multiple ## operators can be chained within a single replacement list. The C Standard specifies that the order of evaluation for multiple ## operators is unspecified. However, this rarely affects the final output provided all intermediate fusions result in valid preprocessing tokens.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More