Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Error: 'x' is not a constant expression, how to fix?

To make it short, here is a minimal example:

struct C {
    const int X = 2;
    int y = 2;
};
void f(C* x) {
    switch(x->y) {
        case x->X: printf("%d", 42); break;
        case 123: printf("foo");
    }
}
int main()
{
    C c;
    f(&c);
    return 0;
}

Why is the compiler complaining error: 'x' is not a constant expression and how to fix it?

like image 269
mskr Avatar asked Nov 05 '25 15:11

mskr


1 Answers

Case labels inside switch accept only compile-time constant expressions. x->X is not a constant expression; hence it could not be used as a case label.

Replace the switch statement with an if to fix this problem:

if (x->y == x->X) {
    printf("%d", 42);
} else if (x->y == 123) {
    printf("foo");
}
like image 160
Sergey Kalinichenko Avatar answered Nov 07 '25 09:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!