Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Preprocessor

The # (stringify) operator

Reference for the C # operator: turn a macro argument into a string literal, the two-step trick to expand macros first, and how spacing and quotes are treated.

Inside a function-like macro, the # operator turns the argument that follows it into a string literal. #x becomes "x" containing the exact tokens the caller wrote. This is how assert can print the failing expression and how test frameworks can print what they are checking.

The argument is not macro-expanded before stringification. To stringify the value of a macro rather than its name, use two levels: an outer macro that expands its argument and an inner one that applies #.

C
#define STR(x) #x
STR(a + b)      /* "a + b" */

Try it

C Printing the expression and its value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C The two-step trick

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#define MACRO(param) ... #param ...
Name Description
#param Replaced by a string literal made from the argument's tokens (leading and trailing white space removed; each run of white space inside becomes one space).

Errors: # must be followed by a macro parameter in function-like macros; anything else is a constraint violation. The resulting string literal must be valid. Stringifying something that yields an invalid escape sequence, such as a lone backslash outside a string or character constant, is undefined behavior.

Usage notes

  • No expansion happens first. STR_DIRECT(VERSION_MAJOR) gives "VERSION_MAJOR". The extra indirection STR(x) STR_DIRECT(x) makes the argument expand before it is passed on.
  • Quotes and backslashes are escaped when the argument contains string or character literals: STR_DIRECT("a\n") produces "\"a\\n\"".
  • Spacing is normalized: comments are removed, and a + b becomes "a + b".
  • Commas split arguments. STR(f(a, b)) is fine (the commas are inside parentheses) but STR(a, b) is two arguments. Use variadic macros with #__VA_ARGS__ for lists.
  • Common uses: assertion messages, logging the name of a variable or function, building version strings, test reports, enum-to-name tables (see X macros).
  • Not a runtime feature. The string is built by the preprocessor, so you cannot stringify a runtime value. Use snprintf for that.
  • Result is a plain char string literal and can be concatenated with neighbouring literals.