Originally posted by bennyandthejets
I don't understand why it must be const.
It's just the design of the switch statement. Each case label must have a constant value. By restricting the cases to constant values, it allows the compiler to make more aggressive optimizations on the jump table.
Try this in your compiler:
Code:
#include <iostream>
using namespace std;
int main()
{
int one = 1;
int two = 2;
int val = 1;
switch(val)
{
case one: cout << "one" << endl; break;
case two: cout << "two" << endl; break;
}
return 0;
}
I get the following errors:
$ g++ test.cpp
test.cpp: In function `int main()':
test.cpp:14: case label does not reduce to an integer constant
test.cpp:15: case label does not reduce to an integer constant
However, change it to this:
Code:
#include <iostream>
using namespace std;
int main()
{
const int one = 1;
const int two = 2;
int val = 1;
switch(val)
{
case one: cout << "one" << endl; break;
case two: cout << "two" << endl; break;
}
return 0;
}
And it compiles without errors.