Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
#define CONCAT(a, b) a ## b
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.
#define CONCAT(x, y) x ## y
#define PREFIX my_

// Yields the token: PREFIXsuffix (PREFIX is not expanded)
CONCAT(PREFIX, suffix) 
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.
#define CONCAT_PRIMITIVE(x, y) x ## y
#define CONCAT_EVALUATED(x, y) CONCAT_PRIMITIVE(x, y)

#define PREFIX my_

// Phase 1: CONCAT_EVALUATED expands arguments -> CONCAT_PRIMITIVE(my_, suffix)
// Phase 2: CONCAT_PRIMITIVE concatenates -> my_suffix
CONCAT_EVALUATED(PREFIX, suffix)

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.
#define FUSE3(a, b, c) a ## b ## c

// Yields the single token: var_x_99
FUSE3(var, _x_, 99)
Master C with Deep Grasping Methodology!Learn More