Understanding switch + foreach
Ali Çehreli
acehreli at yahoo.com
Mon Apr 7 18:57:03 PDT 2014
Firest, complete code to save others' time:
import std.stdio;
import std.typetuple;
void main()
{
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;
}
}
On 04/07/2014 03:30 PM, Matej Nanut wrote:
> 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))
Ok, that's a compile-time foreach.
> {
> case c: "Found %s!".writefln(c);
> break;
That's interesting. Since a compile-time foreach is expanded at compile
time, what happens to a break statement in it? Do we break out of the
foreach statement or do we insert a break statement?
Apparently, the break inside foreach belongs to the switch-case.
> }
> break; // Default always gets executed without this break.
> default:
I think needing that break is a bug. Meanwhile, moving the default block
before the foreach seems to be a workaround.
> "Not found %s :(".writefln(key);
> break;
> }
>
> One after each case and another one after the foreach.
>
> Thanks,
> Matej
>
Ali
More information about the Digitalmars-d-learn
mailing list