Boolean in ifdef: is “#ifdef A && B” the same as “

2019-01-21 15:38发布

In C++, is this:

#ifdef A && B

the same as:

#if defined(A) && defined(B)

?

I was thinking it wasn't, but I haven't been able to find a difference with my compiler (VS2005).

6条回答
趁早两清
2楼-- · 2019-01-21 15:58

Conditional Compilation

You can use the defined operator in the #if directive to use expressions that evaluate to 0 or 1 within a preprocessor line. This saves you from using nested preprocessing directives. The parentheses around the identifier are optional. For example:

#if defined (MAX) && ! defined (MIN)  

Without using the defined operator, you would have to include the following two directives to perform the above example:

#ifdef max 
#ifndef min
查看更多
女痞
3楼-- · 2019-01-21 16:01

I think maybe OP want to ask about the statment "#if COND_A && COND_B", not "#ifdef COND_A && COND_B"...

They are also different. "#if COND_A && COND_B" can judge logic express, just like this:

#if 5+1==6 && 1+1==2
....
#endif

even, a variable in your code also can be used in this macro statment:

int a = 1; 
#if a==1 
...
#endif 
查看更多
狗以群分
4楼-- · 2019-01-21 16:06

As of VS2015 none of the above works. The correct directive is:

#if (MAX && !MIN)

see more here

查看更多
女痞
5楼-- · 2019-01-21 16:15

For those that might be looking for example (UNIX/g++) that is a little different from the OP, this may help:

`

#if(defined A && defined B && defined C)
    const string foo = "xyz";
#else
#if(defined A && defined B)
    const string foo = "xy";
#else
#if(defined A && defined C)
    const string foo = "xz";
#else
#ifdef A
    const string foo = "x";
#endif
#endif
#endif
#endif
查看更多
成全新的幸福
6楼-- · 2019-01-21 16:19

The following results are the same:

1.

#define A
#define B
#if(defined A && defined B)
printf("define test");
#endif

2.

#ifdef A
#ifdef B
printf("define test");
#endif
#endif
查看更多
女痞
7楼-- · 2019-01-21 16:21

They are not the same. The first one doesn't work (I tested in gcc 4.4.1). Error message was:

test.cc:1:15: warning: extra tokens at end of #ifdef directive

If you want to check if multiple things are defined, use the second one.

查看更多
登录 后发表回答