Preprocessor #s, ##s, and other weird stuff


In the post on strings for enums , I used two types of pound symbols in the preprocessor macros: # and ##. Here’s some more detail:

The first preprocessor macro is ##, which means to concatenate what comes after it with what was before. For example:

#define FOO(x) BAR##x
FOO(f)
FOO(test)

will produce (not as legal C, of course):

BARf
BARtest

The second macro is #. That will produce a quoted string from the given argument:

#define FOO(x) #x
FOO(bar)

produces:

"bar"

Note that you cannot use # on non variables. Thus, the following is illegal:

#define FOO(x) #TEST x

If you want to quote the generated output of a macro, it has to be done in stages:

#define STRINGIFY(x) #x
#define FOO(x) STRINGIFY(TEST##x)

FOO(bar)

will produce

"TESTbar"

Enjoy


One response to “Preprocessor #s, ##s, and other weird stuff”

Leave a Reply

Your email address will not be published. Required fields are marked *