Understanding switch + foreach
Steven Schveighoffer
schveiguy at yahoo.com
Tue Apr 8 08:14:58 PDT 2014
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.
Second, I think the issue is likely a bug with the break exiting the wrong
scope. 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
More information about the Digitalmars-d-learn
mailing list