Home > Net >  Can I test the value of a preprocessor directive?
Can I test the value of a preprocessor directive?

Time:05-25

I have a preprocessor directive that I do not set, so I cannot change it, it is either true or false.

Normally I would have done :

#ifdef DIRECTIVE
// code
#endif

But this will always run, since DIRECTIVE is always defined.

Is there a way that I can do basically the equivalent of:

#if DIRECTIVE
#endif

I guess I could do

bool DirectiveValue = DIRECTIVE;
if (DirectiveValue){

}

But I was really hoping the second code block was possible in some way.

Thanks for any insight!

CodePudding user response:

The preprocessor has an #if statement, so you can do things like: #if DIRECTIVE, which (just like in C normally) tests as false if the value of he expression is zero, and true if the value of the expression is non-zero.

Although it's not clear whether it provides a real advantage for you, there's also a kind of intermediate form: if constexpr (DIRECTIVE), which is evaluated at compile time, no run time, so it resembles an #if to some degree in that way--but still using normal C syntax, and integrated with the language in general, instead of being its own little thing with slightly different rules than the rest of the compiler.

CodePudding user response:

you can evaluate a boolean statement after the #if so this code is valid:

#if (DIRECTIVE == true)
// code
#endif

If you have more complicated checks, worth noting is the defined keyword, which returns 0 or 1 if a symbol is defined. This and the ability to write boolean statements allows you to create checks like this:

#define DIRECTIVE_A
#define DIRECTIVE_B

#if defined(DIRECTIVE_A) && defined(DIRECTIVE_B)
// code
#endif
  • Related