[Issue 18912] [REG 2.080 git] "switch skips declaration" of foreach variable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun May 27 19:37:45 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=18912

ag0aep6g <ag0aep6g at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |ag0aep6g at gmail.com
         Resolution|---                         |INVALID
           Severity|normal                      |regression

--- Comment #1 from ag0aep6g <ag0aep6g at gmail.com> ---
(In reply to JR from comment #0)
> Is this a regression or was my code always broken?

As far as I see, the error is good, and your code should not be allowed. So I'm
closing this as invalid. But please feel free to reopen if you disagree with my
reasoning.

Note that the compiler complains about the `member` variable, not
`memberstring`. You're not using `member` in your code, so you don't see that
it's broken, but it is.

For example, you can try printing `member` in the case statement:

----
struct Foo
{
    string abc, def;
}

void main()
{
    Foo foo = Foo("hello", "world");
    switch ("abc")
    {
        foreach (immutable n, ref member; foo.tupleof)
        {
            enum memberstring = __traits(identifier, Foo.tupleof[n]);
            case memberstring:
                import std.stdio;
                writeln(member); /* prints garbage and/or crashes */
                break;
        }

    default:
        break;
    }
}
----

You can use `static foreach` to get a compile-time loop without declaring a
broken `member` variable:

----
struct Foo
{
    string abc, def;
}

void main()
{
    Foo foo = Foo("hello", "world");
    sw: switch ("abc")
    {
        static foreach (immutable n; 0 .. foo.tupleof.length)
        {{
            enum memberstring = __traits(identifier, Foo.tupleof[n]);
            case memberstring:
                import std.stdio;
                writeln(foo.tupleof[n]); /* Prints "hello". */
                break sw;
        }}

    default:
        break;
    }
}
----

--


More information about the Digitalmars-d-bugs mailing list