Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 952
einpoklum Avatar asked Nov 19 '18 16:11

einpoklum


People also ask

What is the point of constexpr functions?

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.

What is if constexpr in C++?

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


1 Answers

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.

like image 152
Nicol Bolas Avatar answered Oct 20 '22 09:10

Nicol Bolas