On 09/04/2015 09:39 PM, Paul wrote:
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?
The switch statement is quite unstructured. You can have your case
statements basically at arbitrary points where a statement is expected:
import std.stdio;
int main(){
int x=2;
switch(x){
do{
for({case 0:};){} x--;
case 1: x--;
if(false){
default: writeln("!");
return 0;
}
}while(true);
}
}
The only case where statements before the first case/default are
potentially useful is when there is some way to jump back there. One
could use goto or something like
https://en.wikipedia.org/wiki/Duff%27s_device
It's not a very common thing to do though, and I don't think anyone
would be sad if there was a dead code warning for the case where the
code before the case statements cannot actually be reached. It's not
done though. DMD never warns about dead code.