Preprocessor checking defined
I can check predefined value like:
#ifdef SOME_VAR
// Do something
#elif
// Do somethi开发者_Python百科ng 2
#endif
If I have to check 2 values instead of 1. Are there any operator:
#ifdef SOME_VAR and SOME_VAR2
// ...
#endif
Or I have to write:
#ifdef SOME_VAR
#ifdef SOME_VAR2
// At least! Do something
#endif
#endif
The standard short-circuiting and operator (&&
) along with the defined
keyword is what is used in this circumstance.
#if defined(SOME_VAR) && defined(SOME_VAR2)
/* ... */
#endif
Likewise, the normal not operator (!
) is used for negation:
#if defined(SOME_VAR) && !defined(SOME_OTHER_VAR)
/* ... */
#endif
You can use the defined
operator:
#if defined (SOME_VAR) && defined(SOME_VAR2)
#endif
#ifdef
and #ifndef
are just shortcuts for the defined
operator.
You can write:
#if defined(SOME_VAR) && defined(SOME_VAR2)
// ...
#endif
#if defined(A) && defined(B)
One alternative is to get away from using #ifdef and just use #if, since "empty symbols" evaluate to false in the #if test.
So instead you could just do
#if SOME_VAR && SOME_OTHER_VAR
// -- things
#endif
But the big side effect to that is that you not only need to #define your variables, you need to define them to be something. E.g.
#define SOME_VAR 1
#define SOME_OTHER_VAR 1
Commenting out either of those #defines will make the above #if test fail (insofar as the enclosed stuff not being evaluated; the compiler will not crash or error out or anything).
精彩评论