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?
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;