switch ( Expression ) ScopeStatement

Tim Matthews tim.matthews7 at gmail.com
Mon Jul 6 19:57:39 PDT 2009


Derek Parnell wrote:
> On Mon, 06 Jul 2009 22:10:20 -0400, bearophile wrote:
> 
>> Derek Parnell:
>>> is valid syntax! Why is that?
>> To allow train-wrecks like this one:
>>
>> version(Tango) import tango.stdc.stdio;
>> void main(char[][] args) {
>>   if (args.length > 1)
>>     switch (args[1]) {
>>       int x = 1; // This initialization to 1 doesn't happen,
>>                  // it's the same as int x = void;
>>       case "1": printf("1! x=%d\n", x); break;
>>       case "2": printf("2! x=%d\n", x); break;
>>     }
>> }
> 
> No quite the same thing, actually. You have highlighted another quirk with
> switch though. 
> 
> My question was really about why is it that the first token after the "(
> Expression )" did not have to be a left-brace, but could be any statement
> at all. 
> 
>   switch(x) funcA();
>   switch(x) switch (y) {};
> 
> Just seems wrong somehow but I'm positive that the experts have a perfectly
> rational answer. I just hope I can understand it.
> 

Switch is really a neat form of comparison and gotos but with actual 
labels replaced with a case statement. A block statement is usually used 
to have more than one case statement valid. This is valid code but 
uncomment the next line and it becomes invalid:

module test;

import tango.io.Stdout;

void main(char[][] args)
{
   if (args.length > 1)
     switch (args[1])
       case "1": Stdout("1"); break;
       //case "2": Stdout("2"); break; //uncomment and error

}


More information about the Digitalmars-d-learn mailing list