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?
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.
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.
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.
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.
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;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With