Understanding switch + foreach

Timon Gehr timon.gehr at gmx.ch
Thu Apr 17 07:26:01 PDT 2014


On 04/17/2014 03:15 PM, Steven Schveighoffer wrote:
>>
>
> But should a foreach over a tuple a breakable statement?

Well, it is a foreach statement.

It is on the other hand not too clear what to do about 'static foreach', 
but I am leaning towards banning non-labelled break and continue inside it.

> Basically, the above seems to me it should be equivalent to:
>
> case 1:
>     writefln("Found %s!", 1);
>     break;
> case 2:
>     writefln("Found %s!", 2);
>     break;
> ...
>
> The foreach should be gone once the foreach is executed at compile-time.
> ...

So are the break statements. The lowering is more along the lines of:

{
     case 1:
         writefln("Found %s!", 1);
         goto Lbreakforeach;
     case 2:
         writefln("Found %s!", 2);
         goto Lbreakforeach;
}
Lbreakforeach:;

> If the break breaks the foreach, why isn't just case 1 produced? That
> would be an actual break in the foreach, no?
>
> -Steve

No. You don't know the dynamic behaviour of the code at runtime just by 
unrolling the foreach body.

import std.stdio;
alias Seq(T...)=T;

void main(){
     int x,y,z;
     readf("%d %d %d",&x,&y,&z);
     alias a=Seq!(x,y,z);
     auto b=[x,y,z];
     foreach(v;a){
         if(v==2) break;
         writeln(v);
     }
     foreach(v;b){
         if(v==2) break;
         writeln(v);
     }
}



More information about the Digitalmars-d-learn mailing list