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.
// 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; }
Token pasting ##:
a ## b concatenates tokens a and b
Stringification #:
#expr converts expr to string literalCombined usage:
Common gotchas:
## must produce valid token## often neededModern alternatives: