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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With