How, exactly, does the double-stringize trick work?

Yes, it’s guaranteed.

It works because arguments to macros are themselves macro-expanded, except where the macro argument name appears in the macro body with the stringifier # or the token-paster ##.

6.10.3.1/1:

… After the arguments for the
invocation of a function-like macro
have been identified, argument
substitution takes place. A parameter
in the replacement list, unless
preceded by a # or ## preprocessing
token or followed by a ##
preprocessing token (see below), is
replaced by the corresponding argument
after all macros contained therein
have been expanded…

So, if you do STR1(THE_ANSWER) then you get “THE_ANSWER”, because the argument of STR1 is not macro-expanded. However, the argument of STR2 is macro-expanded when it’s substituted into the definition of STR2, which therefore gives STR1 an argument of 42, with the result of “42”.

Leave a Comment