Tag Archives: a label can only be part of statement and a declaratioin is not a statement

[Solved] A label can only be part of statement and a declaratioin is not a statement

Background of the problem:

A piece of code was written, as follows.

#include<stdio.h>

int main()
{
    int a;switch (a) {
        case 0:
            break;
        case 1:
            int aa;
            break;
        case 2:
            break;
        default:
            break;
    }

    return 0;
}

As shown above, an error will be reported when the code is compiled, with the error prompt “a label can only be part of statement and a declaration is not a statement”

cause of the problem:

It would not have made sense to have a label on a declaration. C99 relaxed that restriction, permitting declarations and statement to be mixed within a block, but the syntax of a labeled-statement was not changed. –Keith Thompson”。

Before C99, all definitions in a code block must be before declaration. Therefore, a label is meaningless before definition. C99 relaxed this restriction, allowing mixed definitions and declarations in code blocks, but the label cannot be changed before the definition

solution:

#include<stdio.h>

int main()
{
    int a;
    switch (a) {
        case 0:
            break;
        case 1:; //Add an empty ';' to mark the empty statement
            int aa;
            break;
        case 2:
            break;
        default:
            break;
    }

    return 0;
}
#include<stdio.h>

int main()
{
    int a;
    int aa;    //Definition before switch
    switch (a) {
        case 0:
            break;
        case 1:
            break;
        case 2:
            break;
        default:
            break;
    }

    return 0;
}

Read More: https://stackoverflow.com/questions/18496282/why-do-i-get-a-label-can-only-be-part-of-a-statement-and-a-declaration-is-not-a