Member-only story

Stringifying your C++ MACRO

Rahul Bhadani
2 min readNov 8, 2020

--

Image Courtesy: Liam Briese (https://unsplash.com/photos/pH3OM-Vy3FM)

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:

--

--

Rahul Bhadani
Rahul Bhadani

Written by Rahul Bhadani

Asst. Professor, @UAH | @uarizona PhD, ECE | Intelligent Transportation & Quantum Science Researcher | Donation: https://www.buymeacoffee.com/rahulbhadani

No responses yet