define macro expanded to literal # [duplicate]
Possible Duplicate:
c++ preprocessor macro expansion to another preprocessor directive
My question is very simple: I want to use开发者_开发百科 "#" in the macro expansion, for example, to define a marco 'M(X)':
#define M(X) #ifdef FOO \
X=1 \
#else \
X=2
I tried to use '\' to escape the '#', but the '\' is interpreted as the newline for macro expansion, and not as the escape character. So how to use '#' in the macro expansion?
Thanks folks!
Sorry, but you cannot have a macro emit another macro because the pre-processor is single pass. Also from the c99 standard:
(6.10.3.4 paragraph 3):
3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, ...
c++ has something similar as well.
You could do the opposite:
#ifdef FOO
#define M(X) X=1
#else
#define M(X) X=2
#endif
As @Evan points out, macro expansion is done in a single pass, so your example will not work. However, here is an alternative that does what you want, albeit in a few more lines.
#ifdef FOO
#define FOOVAL 1
#else
#define FOOVAL 2
#endif
#define M(X) X=FOOVAL
精彩评论