Can switch statements use variables?

∥☆過路亽.° 提交于 2019-12-23 15:26:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!