Stringifying your C++ MACRO

Image for post
Image for post

Do you know that you can also stringify the MACRO?

Sometimes you want to convert MACRO arguments into a string constant. This is achieved by the stringification of MACRO.

“Stringification” means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in “foo (z)”.

In the C & C++ preprocessor, stringification is an option available when macro arguments are substituted into the macro definition. In the body of the definition, when an argument name appears, the character # before the name specifies the stringification of the corresponding actual argument when it is substituted at that point in the definition. The same argument may be substituted in other places in the definition without stringification if the argument name appears in those places with no #.

But note that there is no way to combine an argument with surrounding text and stringify it all together. Instead, you can write a series of adjacent string constants and stringified arguments. The preprocessor will replace the stringified arguments with string constants. The C compiler will then combine all the adjacent string constants into one long string.

Here is an example of a macro definition that uses stringification:

#define WARN_IF(EXP) \

All leading and trailing whitespace in the text being stringified is ignored.

Any sequence of whitespace in the middle of the text is converted to a single space in the stringified result. Comments are replaced by white space long before stringification happens, so they never appear in the stringified text. There is no way to convert a macro argument into a character constant. If you want to stringify the result of the expansion of a macro argument, you have to use two levels of macros.

Stringification in C involves more than putting double-quote characters around the fragment. The preprocessor backslash-escapes the quotes surrounding embedded string constants, and all backslashes within a string and character constants, in order to get a valid C string constant with the proper contents. Thus, stringifying p = “foo\n”; results in

“p = \”foo\\n\”;”

However, backslashes that are not inside string or character constants are not duplicated: \n by itself stringifies to “\n”.

The following example prints the text “now is the time”

#define now then
#define is was
#define print(stuff) std::cout<<"["#stuff "]\n"
print(now is the time)

Written by

Automation, Quantification, and Communication. PhD, Electrical Engineering

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store