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 #.
#define STR(x) #x STR(a + b) /* "a + b" */
Try it
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.
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
#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 indirectionSTR(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 + bbecomes"a + b". - Commas split arguments.
STR(f(a, b))is fine (the commas are inside parentheses) butSTR(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
snprintffor that. - Result is a plain
charstring literal and can be concatenated with neighbouring literals.
Related
- The ## operator, #define, assert macro
- Tutorial: Macros