问题描述
我一直想知道这 - 你为什么不能在一个switch语句中的case标签后声明变量?在C ++中,可以声明变量pretty随时随地得多(并宣布他们接近第一次使用显然是一件好事),但下面依然是行不通的:
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'的初始化是由案例标签
这似乎是在其他语言的限制太多。这是为什么这样的问题?
This seems to be a limitation in other languages too. Why is this such a problem?
推荐答案
案例声明仅是标签。这意味着,编译器会间preT这与直接跳转到的标签。在C ++中,这里的问题是范围之一。你花括号定义范围为开关语句中的一切。这意味着你只剩下在那里跳将进一步进行到code跳过初始化范围。以正确的操作方法是定义特定于该情况下,语句的范围,并在其中定义变量。
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. 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语句声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!