Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration after goto Label

Today I found one interesting thing. I didn't know that one can't declare a variable after a goto label.

Compiling the following code

#include <stdio.h> int main() {     int x = 5;     goto JUMP;     printf("x is : %d\n",x); JUMP:     int a = 0;  <=== giving me all sorts of error..     printf("%d",a); } 

gives errors like

temp.c: In function ‘main’: temp.c:7: error: expected expression before ‘int’ temp.c:8: error: ‘a’ undeclared (first use in this function) temp.c:8: error: (Each undeclared identifier is reported only once temp.c:8: error: for each function it appears in.) 

Now what is the logic behind that? I heard that one cannot create variables inside the case statements of switch. Since JUMP is inside the same scope (the scope of main function, in my case) of the goto statement, I believe that scope is not an issue here. But then, why am I getting this error?

like image 514
Krishnabhadra Avatar asked Dec 05 '11 11:12

Krishnabhadra


People also ask

How do you declare goto?

There are two ways to call the goto statement. goto label; A label's name is a user defined identifier and is distinguished by the colon that immediately follows its name. The statement immediately followed after “label:” is the statement to be executed after goto statement.

Are goto labels scoped?

Labels are the only identifiers that have function scope: they can be used (in a goto statement) anywhere in the same function in which they appear.

Is goto a variable?

A goto statement is allowed to jump within the scope of a variable length array, but not past any declarations of objects with variably modified types. The following example shows a goto statement that is used to jump out of a nested loop. This function could be written without using a goto statement.

What is label goto statement?

The goto statement can be used to alter the normal flow of control in a program. This statement causes the program to jump to a specified label.


2 Answers

The syntax simply doesn't allow it. §6.8.1 Labeled Statements:

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

Note that there is no clause that allows for a "labeled declaration". It's just not part of the language.

You can trivially work around this, of course, with an empty statement.

JUMP:; int a = 0; 
like image 85
Stephen Canon Avatar answered Sep 19 '22 18:09

Stephen Canon


You want a semi-colon after the label like this:

 #include <stdio.h>  int main() {      int x = 5;      goto JUMP;      printf("x is : %d\n",x);  JUMP: ;     /// semicolon for empty statement      int a = 0;       printf("%d",a);  }     

Then your code compiles correctly for the C99 standard, with gcc -Wall -std=c99 -c krishna.c (I'm using GCC 4.6 on Debian/Sid/AMD64).

like image 40
Basile Starynkevitch Avatar answered Sep 19 '22 18:09

Basile Starynkevitch