const question re: switch statement

Sep 24, 2012 at 4:07pm
Can anyone explain why 'case y' below, throws the error : 'y cannot appear in a constant expression' .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
int x =3;
const int y = x;
int z = 5;

switch(x ){
//next line causes problem
    case y:
        ;
        break;

}

return 0;
}
Sep 24, 2012 at 4:20pm
Why is there a semi-colon under 'y'?

And 'x' is equal to 3 and can be changed in the program, while 'y' cannot be changed.

So if you changed 'x', 'y' would be trying to change to what 'x' is but can't.

If you understand what I mean, change 'x' into a const too and it will work
Sep 24, 2012 at 4:23pm
So if you changed 'x', 'y' would be trying to change to what 'x' is but can't.

No. y is a copy of x. Changing x will not affect y.

The problem is that you can only use compile time constants in the case labels. y is not known at compile time so it can't be used here.
Topic archived. No new replies allowed.