C Language | Preprocessing | Stringification

This article explains how to convert code passed to a function-like macro into a string. It lets you pass non-string text to a macro and convert it into a string during expansion.

Function-Like Macros and the Stringification Operator

A preprocessing operator available in function-like macros converts a sequence of tokens received as a parameter into a string. It analyzes the tokens and expands them with quotation marks. This makes it possible to create macros that automatically convert numbers and token sequences into strings.

To stringify a token sequence, place the # operator before a macro parameter.

#define TOSTRING(param) #param

Because this is a macro, the token sequence passed to param is not restricted. The # operator stringifies any token sequence.

TOSTRING(1234) → "1234"

TOSTRING(int iValue = 10\n) → "int iValue = 10\\n"

TOSTRING("Kitty") → "\"Kitty\""

This conversion occurs at the source-text level before compilation, not dynamically while the program runs. The stringification operator converts quotation marks into \" and backslashes into \\, preserving the original tokens in string form.

Code 1

#include <stdio.h>
#define PRINTLN(string) printf(#string "\n")

int main() {
  PRINTLN(0xFF);
  PRINTLN(Kitty on your lap);
 PRINTLN(Kernighan and Ritchie wrote "hello, world\n" on their book.);
  return 0;
}

The PRINTLN() macro in Code 1 stringifies its argument and displays it with printf(). The last example includes the token "hello, world\n", which the preprocessor converts to \"hello, world\\n\". The quotation marks and escape sequence are therefore displayed literally.