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

c gcc
user1952500 picture user1952500 · Aug 28, 2013 · Viewed 139.5k times · Source

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 a {} block, compilation succeeds.

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

This error is from a gcc compiler

Answer

Renan Gemignani picture Renan Gemignani · Aug 28, 2013

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

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