Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? [duplicate]

Tags:

c

gcc

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

like image 896
user1952500 Avatar asked Aug 28 '13 19:08

user1952500


People also ask

Can only be part of a statement and a declaration is not a statement?

The “a label can only be part of a statement and a declaration is not a statement” error occurs in C when it encounters a declaration immediately after a label. The C language standard only allows statements​ to follow a label. The language does not group declarations in the same category as statements.

What are labels in C?

C. In C a label identifies a statement in the code. A single statement can have multiple labels. Labels just indicate locations in the code and reaching a label has no effect on the actual execution.


2 Answers

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);
}
like image 133
Renan Gemignani Avatar answered Oct 01 '22 19:10

Renan Gemignani


This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}
like image 45
zwol Avatar answered Oct 01 '22 21:10

zwol