digito_evo
digito_evo

Reputation: 3682

#if Vs if constexpr

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
}

Upvotes: 3

Views: 711

Answers (2)

ChrisMM
ChrisMM

Reputation: 10103

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:

Upvotes: 3

0x5453
0x5453

Reputation: 13599

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.

Upvotes: 3

Related Questions