Whiley / RFCs

Request for Comment (RFC) proposals for substantial changes to the Whiley language.
3 stars 2 forks source link

Switch Statement Fall Thru #93

Open DavePearce opened 3 years ago

DavePearce commented 3 years ago

Suggestion: Require all switch cases are terminated with either break, continue or return.

lojikil commented 3 years ago

Do switch statement's cases currently fall through? it doesn't look that way, but as long as we keep that enforcement I think this wouldn't be terrible (although I'm a fan of not having to require a break for each case if we know that we don't fall through). If it does fall through, I think that's a huge win.

DavePearce commented 3 years ago

No, they don't fall through like C or Java. That's a neat idea, but the problem is that people get confused and assume they do fall through. Hence, requiring an explicit break would avoid any confusion. They also allow multiple values in a case, so most of the uses of fall through are still supported:

import uint from std::integer 

function wierd(uint x) -> (uint r)
ensures r > 1:
    //
    switch x:
        case 0,1:
            x = 2
        default:
            assert x >= 2
    //
    return x

Kinda artificial example, but you get the idea. The above would then become:

    switch x:
        case 0,1:
            x = 2
            break
        default:
            assert x >= 2
            break
    //
    return x

Perhaps the last case doesn't need a break though.

Hmmmm, I agree though that the original actually does look better ...

lojikil commented 3 years ago

Ja, personally I like the first one better, and it's easier to see how you stack cases: you add N conditions separated by commas, versus allowing a fall through, and since we don't fall through by default anyway, there's no safety change.