c++if-statementconstexprif-constexpr

C++ if constexpr using a constexpr bool equivalent to plain if?


Are the follow snippets functionally equivalent given the conditional variable that's being checked has been marked as constexpr?

Additionally, is this a correct usage of if constexpr or is it's intended application within a templatized context.

constexpr bool kOn = false;

// Snippet 1
if (kOn) { return true; }

// Snippet 2
if constexpr (kOn) { return true; }

Solution

  • No, the two ifs are not equivalent.

    The 1st one is evaluated at runtime, and code in both of its branches must be well-formed at compile-time.

    The 2nd one is evaluated at compile-time, and code in its unused branch can be ill-formed since its dead code that gets removed by the compiler.

    if constexpr is not dependent on templates.