Tuesday, October 22, 2013

C++ #define containing a further # character to stringify the arg - what it means - Argument Preceded by a # Token in a Macro - thanks to Stack Overflow

Argument Preceded by a # Token in a Macro
#define LINK_ENTITY_TO_CLASS(mapClassName,DLLClassName) \
    static CEntityFactory<DLLClassName> mapClassName( #mapClassName );
This is a macro from the Alien Swarm mod for Half-Life 2, meant to be compiled with MSVC.
I've never seen an argument preceeded by a # in a macro before, and I'm not sure if this is a MSVC specific thing or just uncommon. What does it mean?
This is part of both standard C and C++ and is not implementation-specific. The # preprocessing operator stringizes its argument. It takes whatever tokens were passed into the macro for the parameter designated by its operand (in this case, the parameter mapClassName) and makes a string literal out of them. So, for a simple example,
#define STRINGIZE(x) # x

STRINGIZE(Hello World)
// gets replaced with
"Hello World"
Note that the argument tokens are not macro replaced before they are stringized, so if Hello orWorld were defined as a macro, the result would still be the same. You need to use an extra level of indirection to get the arguments macro replaced (that linked answer discusses the concatenation operator, ##, but applies equally to the stringization operator.
Your answer is right, but I just want to clarify this is a standard part of C preprocessor, and not a MSVC specific thing. –  Swiss Jul 24 '10 at 0:26
@Swiss: Sorry; yes: this is a part of the C language standard. –  James McNellis Jul 24 '10 at 0:31

c++ - Argument Preceded by a # Token in a Macro - Stack Overflow

'via Blog this'

No comments:

Post a Comment