问题描述
我一直想知道 - 为什么不能在 switch 语句中的 case 标签后声明变量?在 C++ 中,您几乎可以在任何地方声明变量(并且在第一次使用时声明它们显然是一件好事)但以下仍然不起作用:
I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
以上给了我以下错误(MSC):
The above gives me the following error (MSC):
'newVal' 的初始化被 'case' 标签跳过
这似乎也是其他语言的限制.为什么会出现这样的问题?
This seems to be a limitation in other languages too. Why is this such a problem?
推荐答案
Case
语句只是标签.这意味着编译器会将其解释为直接跳转到标签.在 C++ 中,这里的问题是范围之一.您的大括号将范围定义为 switch
语句中的所有内容.这意味着您将留下一个范围,在该范围内将进一步跳转到跳过初始化的代码中.
Case
statements are only labels. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch
statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization.
处理此问题的正确方法是定义特定于该 case
语句的范围并在其中定义您的变量:
The correct way to handle this is to define a scope specific to that case
statement and define your variable within it:
switch (val)
{
case VAL:
{
// This will work
int newVal = 42;
break;
}
case ANOTHER_VAL:
...
break;
}
这篇关于为什么不能在 switch 语句中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!