Stringification in the C Preprocessor

A single pound sign (#) is the preprocessing operator for stringification.  It is used when substituting macro parameters into the macro body to tell the preprocessor to convert the parameter to a string constant.  That is, the preprocessor will enclose the parameter in double quotes after it is substituted into the macro body.

To invoke stringification, you precede the name of the parameter in the macro body with the pound sign.  Since the pound sign is used at the point of substitution, if the parameter is substituted into the macro body in more than one place, you can use the parameter as is in some places and as a string literal in others.

The following example shows a macro that could be used to preprocess the parameters to a function named parminfo().

#define PARMINFO(parm, desc)  parminfo(parm, #parm ": " desc)

This macro is expects to be passed the name of a parameter and a string literal describing that contains a description of the parameter.  In the macro body, the name of the parameter is passed on as itself, but it is also prepended to the front of the description.  So, for example, if this macro was called as shown here:

PARMINFO(debug, "Debug level (0-4)");

It would produce the following result:

parminfo(debug, "debug" ": " "Debug level (0-4)");

Since the compiler will concatenate the three string literals together (see "Concatenating String Literals in the Compiler" below), the call to parminfo() would actually look like this:

paraminfo(debug, "debug: Debug level (0-4)");

While stringification can be used anytime you want to pass a literal string into a macro, it is most useful when the parameter needs to be used as both a string literal and as is.

Since the preprocessor will not perform parameter replacement inside a string literal, the only way to pass a parameter into a string literal is to use stringification or to pass a string literal as a parameter.  If you pass a string literal as a parameter, it will remain a string literal when it is substituted.  Stringification allows the parameter to be used as necessary when it is substituted as shown in the example above.  In practice, stringification is usually used for situations where the parameter needs to be used both within a string literal and as is.