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

时间:2013-11-07 06:41:14

标签: c linux gcc

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

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

lab: int a = 10;
     printf("%d\n",a);
}

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

test.c:8: error: a label can only be part of a statement and a declaration is not a statement

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

3 个答案:

答案 0 :(得分:6)

因为此功能称为标记声明

  

C11§6.8.1标记语句

     

<强>语法

labeled-statement:

identifier : statement

case constant-expression : statement

default : statement

一个简单的解决方法是使用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);
}

答案 1 :(得分:5)

在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;
}

答案 2 :(得分:0)

一个简单(但丑陋)的解决方案:

lab: ; 
int a = 10;

空陈述使一切正常 不需要换行符和;之前的空格。