Course contentsShow
← C
Lesson 777 of 1,21911. The Preprocessor and BuildFree lesson

The token-pasting operator `##`

The token-pasting operator ##

What you'll learn: How to use the preprocessor to stitch two pieces of text together to create new variable names or code symbols dynamically.

In previous lessons, we saw how macros can act like a "search and replace" tool. But sometimes, you don't just want to replace a value; you want to manufacture a brand-new name. This is where the token-pasting operator (##) comes in. Think of it as the "glue" of the C preprocessor.

The Glue Logic

When the preprocessor sees ## between two tokens in a macro, it removes the operator and the surrounding whitespace, merging the two pieces into one single word.

Imagine you are building a game and need to create several variables like player1_score, player2_score, and player3_score. Instead of typing them all out, you can use a macro to "build" the variable names for you.

Seeing it in Action

Here is how you might use ## to generate specific variable names on the fly:

#include <stdio.h>

// The macro takes a 'number' and glues it to 'player' and '_score'
#define MAKE_SCORE_VAR(n) player ## n ## _score

int main() {
    // This expands to: int player1_score = 100;
    int MAKE_SCORE_VAR(1) = 100;
    
    // This expands to: int player2_score = 250;
    int MAKE_SCORE_VAR(2) = 250;

    printf("Player 1: %d\n", player1_score);
    printf("Player 2: %d\n", player2_score);

    return 0;
}

Why Use It?

The primary reason to use token-pasting is to avoid repetitive "boilerplate" code. If you have a pattern that repeats with only slight variations in names—like defining a set of similar functions for different data types—## allows you to write a single template macro.

However, be careful! The result of a paste must be a valid C "token." If you try to glue 12 and abc to get 12abc, your compiler will complain because a variable name cannot start with a number. Use the ## glue to make your code more flexible, but always ensure the final "pasted" word follows C's naming rules.

Key takeaway

The ## operator merges two separate text fragments into a single identifier during the preprocessing phase.