switch语句可以使用变量吗? [英] Can switch statements use variables?
本文介绍了switch语句可以使用变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是声明两个int变量并尝试在switch语句中使用它们的代码。这是C ++中的合法操作吗?
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;
}
推荐答案
case
标签必须是整数常数表达式,因此您的示例无效。但是如果 x
更改为:
The case
label must be an integral constant expression, so your example is invalid. But if x
were changed to:
const int x = 3;
那么它是有效的。
这篇关于switch语句可以使用变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文