D's SwitchStatement accepts statements with ridiculous semantics

Don Clugston edibleplutonium at completelysafe.com
Fri Sep 29 09:12:54 UTC 2017


Guess what this prints

----
import std.stdio;

void main()
{
   int i = 0;

   switch (i) for (i = 8; i < 10; ++i)
   {
     case 7:
         writeln(i);
         return;

     default: ;
   }
}
----


Why does this even compile? It's because the grammar is:

SwitchStatement:
     switch ( Expression ) ScopeStatement


and ScopeStatement allows almost anything.
I think the only sane grammar is

SwitchStatement:
     switch ( Expression ) BlockStatement

Initially I thought ScopeStatement was accepted in order to 
enable Duff's device, but it isn't necessary for that. It might 
have originally accepted ScopeStatement to support

E e; switch( e ) with (E) { .... }

Or it may have just been an accident.
But regardless of the original motivation, it allows some truly 
dreadful semantics.
Can we disallow this silliness please?



More information about the Digitalmars-d mailing list