问题
Below is code that declares two int variables and tries to use them in a switch statement. Is this a legal operation in C++? If not, why not?
int i = 0;
int x = 3;
switch (i)
{
case x:
// stuff
break;
case 0:
// other stuff
break;
}
回答1:
The case
label must be an integral constant expression, so your example is invalid. But if x
were changed to:
const int x = 3;
then it's valid.
回答2:
Can switch statements use variables?
Yes. This is fine,
int i = 0;
switch (i) {
}
But, case
statements cannot use variables (they must be constant).
case 0:
// first
break;
case 1:
// second
break;
default:
// other
来源:https://stackoverflow.com/questions/25151730/can-switch-statements-use-variables