switch case中的定义

来源:互联网 发布:centos smb unrec 编辑:程序博客网 时间:2024/05/25 21:35

原文:http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement


C语言 switch 中的 case 不能声明变量:

switch (val)  {  case VAL:    // This won't work  int newVal = 42;    break;case ANOTHER_VAL:    ...  break;


编译会出现类似 “a label can only be part of a statement and a declaration is not a statement” 的错误。

C语言 switch 中的case是标号,它的执行就像 jump 一样,直接跳到可执行的代码处而忽略初始化,或者跳到另一个以“{}”包围的 scope 中。

Case statements are only 'labels'. This means the compiler will interpret this as a jump directly to the label.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;}