仕様によると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;
}