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

The stringizing operator `#`

The stringizing operator #

What you'll learn: How to use the # symbol within a macro to convert a macro argument directly into a literal string.

The Problem: Names vs. Values

Imagine you are writing a debugging tool. You want to print the name of a variable and its current value. Normally, you’d have to type the name twice: once inside quotes for printf to display the text, and once as the variable itself to get the data. This is repetitive and prone to typos.

The C preprocessor has a special trick for this. When you place a # symbol in front of a macro argument, the preprocessor wraps that argument in double quotes. This process is called stringizing.

How it works

Think of the # operator like a "shrink-wrap" machine. Whatever you feed into the macro argument, the # operator wraps it in a permanent layer of quotes, turning code into a string literal before the compiler even sees it.

#include <stdio.h>

// The #x tells the preprocessor: "Take whatever text is passed 
// as x and put double quotes around it."
#define PRINT_INT(x) printf("The variable %s has value: %d\n", #x, x)

int main() {
    int apples = 5;
    int temperature = 72;

    // The preprocessor turns #apples into "apples"
    PRINT_INT(apples);

    // The preprocessor turns #temperature into "temperature"
    PRINT_INT(temperature);

    return 0;
}

Why use it?

The magic here is that the macro "knows" what the code looked like before it was compiled. If you pass PRINT_INT(10 + 5), the #x will literally become the string "10 + 5".

This is incredibly useful for logging, creating error messages that include the failing expression, or building automated testing frameworks. It allows your program to talk about its own source code. Note that this only works inside a #define macro; you cannot use the # operator in standard C functions.

Key takeaway

The # operator turns a macro argument into a string literal by wrapping it in double quotes during the preprocessing phase.