c-token-pasting
Table of Contents
C token pasting
C token pasting uses the ## preprocessor operator to concatenate tokens into a single token. Use #name (stringification) to convert a token to a string. Combined, these enable powerful metaprogramming and code generation.
Use token pasting in X macros and generic code generators; stringification for debug output.
Example
// compile: gcc -o token_paste token_paste.c // run: ./token_paste // description: ## and # preprocessor operators #include <stdio.h> // Token pasting: concatenate tokens #define CONCAT(a, b) a ## b #define FUNC_NAME(name) func_ ## name // Define functions with pasting #define DEFINE_HANDLER(name) \ void func_ ## name(void) { \ printf("Handler: " #name "\n"); \ } DEFINE_HANDLER(start) DEFINE_HANDLER(stop) DEFINE_HANDLER(reset) // Stringification #define STR(x) #x #define ASSERT(expr) \ do { \ if (!(expr)) \ printf("ASSERT FAILED: %s\n", #expr); \ } while(0) int main() { CONCAT(func_, start)(); CONCAT(func_, stop)(); printf("String: %s\n", STR(hello_world)); printf("Macro name: %s\n", STR(CONCAT)); int x = 5; ASSERT(x > 0); ASSERT(x < 0); // Fails, prints "x < 0" return 0; }
Common patterns
Token pasting ##:
a ## bconcatenates tokens a and b- Result must form valid token
- Used in code generation, X macros
Stringification #:
#exprconverts expr to string literal- Useful for error messages, debug output
- Shows original expression text
Combined usage:
- X macros with both operators
- Code generation with pattern matching
- Variadic macro debugging
Common gotchas:
##must produce valid token- Whitespace around
##often needed - Stringification doesn't evaluate, just converts text
Modern alternatives:
- C++ templates (type-safe, clearer)
- Code generators (external tools)
- But token pasting remains pure-C solution
c-token-pasting.md · Last modified: by 127.0.0.1
