Home > Article > Backend Development > How Can I Ensure No `else` Clause is Ever Executed in a C `constexpr if-else` Chain?
Preventing Non-Fulfillment of Constexpr If-Else Clauses
In C , one may encounter the need to assert that all constexpr if conditions within an if-else statement are met. Without such an assertion, the else clause may be taken unexpectedly.
Consider the following code:
if constexpr(condition1){ ... } else if constexpr (condition2) { .... } else if constexpr (condition3) { .... } else { // I want the else clause never taken. But I heard the code below is not allowed static_assert(false); }
One might assume that the else clause would never be taken since all conditions should be mutually exclusive. However, according to the C standard, such an assertion is not allowed.
Solution: Template Dependency
To prevent the else clause from being taken, one must make the discarded statement dependent on the template parameters. This can be achieved using the following code:
template <class... T> constexpr std::false_type always_false{}; if constexpr(condition1){ ... } else if constexpr (condition2) { .... } else if constexpr (condition3) { .... } else { static_assert(always_false<T>); }
Reasoning
The C standard states that a program is ill-formed if no valid specialization can be generated for a template or a substatement within a template. By making the discarded statement dependent on template parameters, the compiler can ensure that no valid specialization can be generated when none of the conditions is met, effectively preventing the else clause from being taken.
The above is the detailed content of How Can I Ensure No `else` Clause is Ever Executed in a C `constexpr if-else` Chain?. For more information, please follow other related articles on the PHP Chinese website!