In C++17, if constexpr
was introduced; however, there doesn't seem to be a switch constexpr
(see here). Why is that? That is, if a compiler supports if constexpr
, is it not also trivial for it to support switch constexpr
(at worst as an if-then-else-if-etc. chain, or multiple if's with some flags to control fallthrough)?
A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.
In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool (until C++23)an expression contextually converted to bool, where the conversion is a constant expression (since C++23).
if constexpr
was ultimately derived from a more sane form of the static if
concept. Because of that derivation, applying the same idea to switch
does not appear to have been considered by the standards committee. So this is likely the primary reason: nobody added it to the paper since it was a restricted form of a syntax where switch
wouldn't have made sense.
That being said, switch
has a lot of baggage in it. The most notable bit being the automatic fallthrough behavior. That makes defining its behavior a bit problematic.
See, one of the powers of if constexpr
is to make the side not taken at compile time be discarded under certain conditions. This is an important part of the syntax. So a hypothetical switch constexpr
would be expected to have similar powers.
That's a lot harder to do with fallthrough, since the case
blocks are not as fundamentally distinct as the two blocks of an if
statement. Especially if you have conditional fallthrough. Now, you could make switch constexpr
not have automatic fallthrough (or fallthrough at all), so that the different sections are distinct. But then you've subtly changed how the syntax works; a non-constexpr
form of switch
behaves differently from the constexpr
form. That's not good.
Yes, you could make it a compile error to not put break;
statements between the labels.
Note that the two main pattern-matching proposals, P1308 and P1260, specifically avoid using switch
, instead inventing a new keyword. They both have constexpr
aspects to them, but they make it abundantly clear that they are not switch/case
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With