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 ##:

Stringification #:

Combined usage:

Common gotchas:

Modern alternatives: