Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

usage of constexpr variable as a case label

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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():
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading