using #if inside a #define

A

anon.asdf

Hello!

How can a #if be used inside a #define?

The following do not work:

#define MAC1(n) \
#if (n = 1) \
printf("hello\n");\
#endif


#define MAC2(n, myif, myend) \
##myif (n == 1) \
printf("hello\n"); \
##myend


#define NOTHING /**/

#define MAC3(n, myif, myend) \
NOTHING ##myif (n == 1) \
printf("hello\n"); \
##myend




/*
MAC1(1);
MAC2(1, "#if", "#endif");
MAC3(1, "#if", "#endif");
*/

Thanks -Albert
 
A

anon.asdf

On Aug 27, 12:48 pm, (e-mail address removed) wrote:
[snip]
/*
MAC1(1);
MAC2(1, "#if", "#endif");
MAC3(1, "#if", "#endif");
*/

usage would rather be:

MAC1(1);
MAC2(1, #if, #endif);
MAC3(1, #if, #endif);

-Albert
 
B

borkhuis

Hello!

How can a #if be used inside a #define?

AFAIK the C-preprocessor is a single pass-processor. The output of the
preprocessor will contain the #if lines, and these are not recognized
by the compiler. So if you want to do this you have to run the
preprocessor multiple times. I expect that your code will be non-
portable.
The only way to do this is to reverse the order: get the #define
inside #if statement. This can be passed by the preprocessor in a
single pass.

Kind regards,
Johan Borkhuis
 
E

Eric Sosman

Hello!

How can a #if be used inside a #define?

It cannot. 6.10.3.4p3:

"The resulting completely macro-replaced preprocessing
token sequence is not processed as a preprocessing
directive even if it resembles one [...]"
The following do not work:
[...]

These are just toys. What problem are you trying to solve?
 
A

anon.asdf

How can a #if be used inside a #define?

It cannot. 6.10.3.4p3:

"The resulting completely macro-replaced preprocessing
token sequence is not processed as a preprocessing
directive even if it resembles one [...]"

Thanks Eric and Johan!
The following do not work:
[...]

These are just toys. What problem are you trying to solve?

The problem is shown in the mail with title:
"static (non-zero) initialization of an array of structs (array of
length #define LEN)"
Aug 27, 1:02 pm
and
Aug 27, 1:08 pm

-> statically initialize each element of an array (whose length is
#define LEN) with the same (non-zero!) value

http://groups.google.com/group/comp...5143e28ce14/df1b37d5d5d0974d#df1b37d5d5d0974d

-Albert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top