Why do I get "the label can only be part of the statement, and the declaration is not an expression" if I have a variable that is initialized after the label?

I have the following simplified code:

#include <stdio.h> int main () { printf("Hello "); goto Cleanup; Cleanup: char *str = "World\n"; printf("%s\n", str); } 

I get an error because a new variable is declared after the label. If I put the content (mainly initialization) after the label in the {} block, compilation succeeds.

I think I understand the reason for the block in the case of the switch, but why should it be used in the case of the label?

This error comes from the gcc compiler

+61
c gcc
Aug 28 '13 at 19:09
source share
2 answers

The language standard simply does not allow this. Labels can be followed only by statements, and declarations are not considered statements in C. The easiest way to get around this is to insert an empty statement after the label, which saves you from tracking the scope as you need inside the block.

 #include <stdio.h> int main () { printf("Hello "); goto Cleanup; Cleanup: ; //This is an empty statement. char *str = "World\n"; printf("%s\n", str); } 
+80
Aug 28 '13 at 19:17
source share

This is a quirk of C. grammar. The label ( Cleanup: cannot appear immediately before the declaration (for example, char *str ...; ), only before the statement ( printf(...); ). This wasn’t a big deal in C89, because ads could only appear at the very beginning of the block, so you can always put a shortcut a bit and avoid the problem. In C99, you can mix ads and code, but you still can't put a shortcut immediately before the ad.

You can put a semicolon immediately after the colon colon (as suggested by Renan) to make an empty expression there; this is what i would do in machine code. Also, raise the ad at the top of the function:

 int main (void) { char *str; printf("Hello "); goto Cleanup; Cleanup: str = "World\n"; printf("%s\n", str); return 0; } 
+16
Aug 28 '13 at 19:16
source share



All Articles