Superfluous code in switch statement

Paul via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 4 12:39:39 PDT 2015


I discovered the other day (during a cut and paste malfunction!) 
that it's possible to have code before the first case in a 
switch. Google tells me that it's legal C code and something I 
read said it could be used for initialization but was rather 
vague.

void main()
{
     import std.stdio;

     int a=1;

     switch(a)
     {
         a=2;
         writeln("hello");

         case 1:
         break;
         case 2:
         break;
         default:

     }
     writeln(a);

}

The code before the 'case' has to be legal D code to pass 
compilation but it seems to have no effect (which is probably a 
good thing!). I was a bit surprised that the compiler (dmd) 
didn't generate a warning when using the -w option.

Can someone explain what's going on here please?



More information about the Digitalmars-d-learn mailing list