Why can we not declare a variable after a switch case colon without using curly braces?

That is how the C grammar is defined. Variable declarations are not considered statements:

int x; //a declaration
int y = 3; //another declaration
x = y + 1; //a statement

A label is required to be followed by a statement. A label plus a declaration is not allowed.

foo: int x; //error
bar: x = y +1; //ok

That is, IMO, inconvenient:

while (...)
{
    //...
    goto end;
    end:   //error, no statement   
}

And remember that a case is just a special kind of label, so:

case 1: int x; //error
case 2: x = y +1; //ok

The issue with braces is that in C they are used to build a compound statement, that of course is a kind of statement. The lines inside the compound statements can be both declarations and statements, all mixed (old C versions only allowed declarations at the beginning, not in the middle). So:

case 1: int x; //error: label plus declaration
case 2: { int x; } //ok: label plus compound statement

As a footnote, since modern C allows to intermix declarations and statements you can also write:

case 1:; int x; //ok: label plus empty statement.

because an isolated ; is an empty statement, it can be used to satisfy the grammar whereever a no-op statement is needed.

Whether to use a ; or a { ... } is a matter of readability. In the end: example I’d use a ;, but in the case: I prefer the {...}.

while (...)
{
    //...
    goto end;
    end:;   //ok, empty statement   
}

switch (...)
{
    case 1: //ok, compound statement
    {
        int x;
    }
}

Of course more creative solutions can be written, such as:

case 1: {} int x; //ok, label plus empty compound statement

Leave a Comment