Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why first part in a label should be statement? and why not declaration?

Tags:

c

linux

gcc

I am getting compilation error when compiling below code.

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

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

When i compile this code it is giving

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

Why first part of a label should be a statement and why not a declaration?

like image 844
Chinna Avatar asked Dec 19 '22 21:12

Chinna


2 Answers

Because this feature is called labeled statement

C11 §6.8.1 Labeled statements

Syntax

labeled-statement:

identifier : statement

case constant-expression : statement

default : statement

A simple fix is to use a null statement (a single 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);
}
like image 127
Yu Hao Avatar answered Dec 24 '22 01:12

Yu Hao


In c according to spec

§6.8.1 Labeled Statements:

labeled-statement:
    identifier : statement
    case constant-expression : statement
    default : statement

In c there is no clause that allows for a "labeled declaration". Do this and it will work:

#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
    }//-------------------------------
}

A label makes the compiler interpret the label as a jump directly to the label. You will have similar problems int this kind of code as well:

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

Again just add a scope block ({ }) and it would work:

switch (i)
{   
   case 1:  
   // This will work 
   {//-------------------------------
       int a = 10;//                 | Scoping
       break;//                      | Solves the issue here as well
   }//-------------------------------
   case 2:  
       break;
}
like image 30
Sadique Avatar answered Dec 24 '22 02:12

Sadique