Search code examples
c++c++17c++20if-constexpr

If there's an if-constexpr, how come there's no switch-constexpr?


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)?


Solution

  • 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.