1

A friend of mine has just joked that this would be possible in C, to which I responded: impossible. It turned out it is possible and compiles without ANY warnings.

#include "stdio.h"

int main(){

    int x = 1;

    switch(x) {
        case 1: 
            printf("1\n");

            while(1) {
                case 2:
                    printf("bad 2\n");          
            }
            break;

        default:
            printf("default\n");
            break;          
    }

}

Setting x to 1 or 2 results in an infinite loop printing bad 2 all the time.

Why? What is going on, how is this even legal???

I am using GCC 4.8.2, Windows, -std=c99 ...


Edit: This question is about why is it legal, if it is legal, and since when. Examples are nice, but not the goal of my question. I'd like to know, if this whole placing of case labels anywhere is a conscious C design, or an accident, or a leaky abstraction / implementation detail leak ?

Parobay
  • 2,549
  • 3
  • 24
  • 36

3 Answers3

2

This is legal. The depending part of a switch is in fact just an arbitrary statement or block, and the case and default labels have just to fulfill the rules of other labels, namely to prefix a statement.

In the example you are giving this makes not much sense, but there are examples, namely the notorious Duff's device that use this kind of features.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • Yeah, I'll read about Duff's in moment, but will treat is an example only. What I am asking is generally, if this was legal C (since when? since always?) and, perhaps, why is this legal? Java would never permit to write such code - switch/case is a separate constuct, whereas here in C, it seems (please confirm), that case is just a label? – Parobay Jan 29 '14 at 09:42
  • @Parobay, I did reply to that no? It is complying with the C standard, and this with any of its version. To your question "why?", my guess would be that C is thought to be a simple language, syntactically. The dependent construct is a statement or block as for any of the other control structures. – Jens Gustedt Jan 29 '14 at 09:45
  • http://en.wikipedia.org/wiki/Duff%27s_device#Mechanism this is pretty nice – Parobay Jan 29 '14 at 10:03
0

The standard example/explanation of this is Duff's device: http://en.wikipedia.org/wiki/Duff's_device

I suggest you read the article and then ask a refined question if there are still unclear areas.

Silex
  • 1,707
  • 17
  • 24
0

Is this legal? Yes it is because syntactically, you may nest a case as many levels deep as you want inside a switch. This is perfectly legal:

switch(a)
{
case 1: break;
{ 
    {
        case 2: break;
    }
}
}

And a while() can be used in place of any statement. The compiler doesn't bother to check what is inside as long as they are all valid C statements.

th33lf
  • 2,177
  • 11
  • 15