Is it correct to use constexpr variable as a case label.
#include <iostream>
int main() {
constexpr int x = 5;
int y = 4;
switch (y) {
case x - 1:
std::cout << "case " << x << std::endl;
break;
case 20:
std::cout << "case 20" << std::endl;
break;
default:
std::cout << "case default" << std::endl;
break;
}
}
>Solution :
It is. cppreference says the case value must be
a constant expression of the same type as the type of condition after conversions and integral promotions
That includes constexpr expressions like a constexpr variable to which you subtract 1 like in your example.
In the standard, that’s [stmt.switch]:
Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression of the adjusted type of the switch condition.
No two of the case constants in the same switch shall have the same value after conversion.
And a constant expression is anything in [expr.const].
For example, you can even use a constexpr function call:
constexpr int caseLabel() {
return 4;
}
// ...
switch (y) {
case caseLabel():