在 c 根据规范
§6.8.1 标记语句:
labeled-statement:
identifier : statement
case constant-expression : statement
default : statement
在 c 中没有允许“标记声明”的子句。这样做,它将起作用:
#include <stdio.h>
int main()
{
printf("Hello 123\n");
goto lab;
printf("Bye\n");
lab:
{//-------------------------------
int a = 10;// | Scope
printf("%d\n",a);// |Unknown - adding a semi colon after the label will have a similar effect
}//-------------------------------
}
标签使编译器将标签解释为直接跳转到标签。在这种代码中,您也会遇到类似的问题:
switch (i)
{
case 1:
// This will NOT work as well
int a = 10;
break;
case 2:
break;
}
再次只需添加一个范围块 ( {
}
) 就可以了:
switch (i)
{
case 1:
// This will work
{//-------------------------------
int a = 10;// | Scoping
break;// | Solves the issue here as well
}//-------------------------------
case 2:
break;
}