gpt4 book ai didi

c++ - switch 语句可以使用变量吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:54 24 4
gpt4 key购买 nike

下面是声明两个 int 变量并尝试在 switch 语句中使用它们的代码。这是 C++ 中的合法操作吗?如果不是,为什么不呢?

int i = 0;
int x = 3;
switch (i)
{
case x:
// stuff
break;

case 0:
// other stuff
break;
}

最佳答案

case 标签必须是一个整型常量表达式,因此您的示例无效。但是,如果将 x 更改为:

const int x = 3;

那么它是有效的。

关于c++ - switch 语句可以使用变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com