Understanding switch + foreach

Timon Gehr timon.gehr at gmx.ch
Thu Apr 17 03:54:39 PDT 2014


On 04/08/2014 05:14 PM, Steven Schveighoffer wrote:
> On Mon, 07 Apr 2014 18:30:30 -0400, Matej Nanut <matejnanut at gmail.com>
> wrote:
>
>> Hello,
>>
>> I don't understand why so many break statements are needed in this
>> construct:
>>
>>     immutable key = 3;
>>     switch (key)
>>     {
>>         foreach (c; TypeTuple!(1, 2, 3, 4, 5))
>>         {
>>             case c: "Found %s!".writefln(c);
>>                     break;
>>         }
>>         break; // Default always gets executed without this break.
>>         default:
>>             "Not found %s :(".writefln(key);
>>             break;
>>     }
>>
>> One after each case and another one after the foreach.
>
> First, let me say this is a cool usage of compile-time foreach, I had
> never thought of that.
> ...

I do this quite often.

> Second, I think the issue is likely a bug with the break exiting the
> wrong scope.

No, this is expected behaviour. break and continue work in any foreach 
statement. break always breaks the innermost breakable statement. (In 
particular, it does not pair up with case statements.)

> You may be able to fix it by labeling the switch scope.
>
> For example:
>
> theswitch:
>     switch(key)
>     {
>
>        ...
>        break theswitch; // should exit the switch.
>     }
>
> I have not tested it.
>
> -Steve

Yes, this works.


More information about the Digitalmars-d-learn mailing list