Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: wrongly nested switch/case blocks surprisingly works

I just discovered the following section in some code I maintain:

switch (m) {
    case 62: { // opening
        // some declarations
        // do some stuff
        break;
    case 63:
        // do some other stuff
        break;
        }      // closing
    default:
        // default stuff
        break;
 }   

The block opening is meant to declaring some local variables, but the closing brace is wrongly placed and occurs after the case 63.

I have never noticed this for months as it compiles well in Visual Studio 2010. I've tried debugging it and both cases work fine.

How can it be ? Is this correct C syntax ?

like image 337
wap26 Avatar asked Jan 28 '13 20:01

wap26


3 Answers

The case statements are just like goto labels and so that is allowed syntax. Duff's device is a famous use-case.

Try to avoid doing it though.

like image 188
Pubby Avatar answered Nov 07 '22 04:11

Pubby


6.8.1 Labeled statements, C99

Any statement may be preceded by a prefix that declares an identifier as a label name. Labels in themselves do not alter the flow of control, which continues unimpeded across them.

i.e. The curly braces have no effect on how the switch-case labels work but it merely creates a new scope.

This explains why the seemingly misplaced curly braces don't result in a syntax error.

like image 5
P.P Avatar answered Nov 07 '22 04:11

P.P


Surprisingly, this is correct syntax per the language standard. You can even do this:

switch (m) break;

or this:

switch (m);

case const-expr: works pretty much like a regular label that you'd use with goto.

like image 4
Alexey Frunze Avatar answered Nov 07 '22 03:11

Alexey Frunze