且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能变量switch语句声明?

更新时间:2022-12-24 14:39:52

案例声明仅是标签。这意味着,编译器会间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;
}