Home > Back-end >  #if Vs if constexpr
#if Vs if constexpr

Time:04-09

Which one is more appropriate for compile-time configurations (such as debug/release), preprocessor directives, or if constexpr?

#define DBG

#if DBG
// some code
#endif

// --------------------------------- or

inline constexpr bool DEBUG { true };

if constexpr ( DEBUG )
{
// some code
}

CodePudding user response:

Note that, if if constexpr is not part of a template, then the other parts of the if (such as the elses) are still compiled and checked for validity.

From cppreference:

If a constexpr if statement appears inside a templated entity, and if condition is not value-dependent after instantiation, the discarded statement is not instantiated when the enclosing template is instantiated .

Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive:

CodePudding user response:

You still generally need #if for this. #if can do things like change what headers you are including, change what functions and types are defined, and change the definitions of other preprocessor directives. if constexpr cannot do any of that.

  • Related