Possible Duplicate:
Convert a preprocessor token to a string
#define num 1234
I want to define a “const char*” based on num, in the sample it would be:
#define num_str "1234"
Can I write a macro statement to achieve this?
NB: 1234 would be changed.
Thanks.
Yes you can, but the macro substitution can get a little strange-looking. The double-macro substitution is there for a reason, and if you think about it for awhile, it will become clear why it is needed.
Running this:
The reason for the double substitution: At first glance one may think this will solve the problem:
But this produces:
which is not what we’re trying to do. If you want the actual expansion of the NUM macro first then that is what you have to do: force the expansion. By forcing the preprocessor to substitute first through an intermediate expansion (as I show at the top of this answer) the passed-in macro is expanded first, then string-ized.
Side Bar: This technique is particularly useful for generating wide-char versions of predefined preprocessor macros that otherwise hold regular strings. For example, the
__FILE__macro. Suppose you wanted a wide-char version of this (a string prepended with ‘L’) You may first think this will work:but expanding this with
__FILE__as in:will result in a compiler error:
"Undefined identifier: L__FILE__"So how can we address this? The same way we did above.
On my system, this produces:
In Closing…
As a consolation prize, we combine everything in this answer into one giant goo-pile, what do we suppose happens when we do this: