[Issue 11070] New: Allow auto statement in a switch statement

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Sep 19 10:40:15 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=11070

           Summary: Allow auto statement in a switch statement
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: andrej.mitrovich at gmail.com


--- Comment #0 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2013-09-19 10:40:13 PDT ---
Currently if you want to handle an unhandled case in a switch statement you can
use a default statement. For example:

-----
import std.string;

auto get() { return "c"; }

void main()
{
    auto res = get();
    switch (res)
    {
        case "a": break;
        case "b": break;
        default:  assert(0, format("Unhandled case: '%s'", res));
    }

    /// res still visible here, we don't want it to be.
}
-----

The problem here is that you're unnecessarily creating the 'res' variable which
you will only use for the default statement. Additionally, such a variable
shouldn't be visible outside the switch statement if it's only going to be used
inside of the switch statement.

I propose we allow an auto statement in the switch statement:

-----
import std.string;

auto get() { return "c"; }

void main()
{
    switch (auto res = get())  // new: allow auto statement
    {
        case "a": break;
        case "b": break;
        default:  assert(0, format("Unhandled case: '%s'", res));
    }
}
-----

This will also eliminate the need for code duplication in switch statements
which use a common label statement, for example:

-----
import std.string;
import std.stdio;

auto get() { return "d"; }

void main()
{
    switch (auto res = get())
    {
        case "a": goto common;
        case "b": goto common;
        case "c": goto common;

        common:
            writefln("Got result: %s", res);
            break;

        default:  assert(0, format("Unhandled case: '%s'", res));
    }
}
-----

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list