0

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!

Community
  • 1
  • 1
lukmac
  • 4,617
  • 8
  • 33
  • 34

3 Answers3

6

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.

Evan Teran
  • 87,561
  • 32
  • 179
  • 238
6

You could do the opposite:

#ifdef FOO
    #define M(X) X=1
#else
    #define M(X) X=2
#endif
peoro
  • 25,562
  • 20
  • 98
  • 150
1

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
EmeryBerger
  • 3,897
  • 18
  • 29