为什么标签中的第一部分应该是声明?为什么不申报?

Chi*_*nna 4 c linux gcc

编译下面的代码时出现编译错误.

#include <stdio.h>
main()
{
    printf("Hello 123\n");
    goto lab;
    printf("Bye\n");

lab: int a = 10;
     printf("%d\n",a);
}
Run Code Online (Sandbox Code Playgroud)

当我编译这段代码时,它正在给予

test.c:8: error: a label can only be part of a statement and a declaration is not a statement
Run Code Online (Sandbox Code Playgroud)

为什么标签的第一部分应该是声明,为什么不是声明呢?

Yu *_*Hao 6

因为此功能称为带标签的语句

C11§6.8.1标记语句

句法

labeled-statement:

identifier : statement

case constant-expression : statement

default : statement
Run Code Online (Sandbox Code Playgroud)

一个简单的解决方法是使用null语句(单个semecolon ;)

#include <stdio.h>
int main()
{
    printf("Hello 123\n");
    goto lab;
    printf("Bye\n");

lab: ;         //null statement
    int a = 10;
    printf("%d\n",a);
}
Run Code Online (Sandbox Code Playgroud)


Sad*_*que 5

在c根据规范

§6.8.1标签声明:

labeled-statement:
    identifier : statement
    case constant-expression : statement
    default : statement
Run Code Online (Sandbox Code Playgroud)

在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
    }//-------------------------------
}
Run Code Online (Sandbox Code Playgroud)

标签使编译器将标签解释为直接跳转到标签.在这种代码中你也会遇到类似的问题:

switch (i)
{   
   case 1:  
       // This will NOT work as well
       int a = 10;  
       break;
   case 2:  
       break;
}
Run Code Online (Sandbox Code Playgroud)

再次添加一个范围块({ }),它会工作:

switch (i)
{   
   case 1:  
   // This will work 
   {//-------------------------------
       int a = 10;//                 | Scoping
       break;//                      | Solves the issue here as well
   }//-------------------------------
   case 2:  
       break;
}
Run Code Online (Sandbox Code Playgroud)