Switch Statements – Why Explicit Fall-Through is Rarely Used

switch statement

I was reading Why do we have to use break in switch?, and it led me to wonder why implicit fall-through is allowed in some languages (such as PHP and JavaScript), while there is no support (AFAIK) for explicit fall-through.

It's not like a new keyword would need to be created, as continue would be perfectly appropriate, and would solve any issues of ambiguity for whether the author meant for a case to fall through.

The currently supported form is:

switch (s) {
    case 1:
        ...
        break;
    case 2:
        ... //ambiguous, was break forgotten?
    case 3:
        ...
        break;
    default:
        ...
        break;
}

Whereas it would make sense for it to be written as:

switch (s) {
    case 1:
        ...
        break;
    case 2:
        ...
        continue; //unambiguous, the author was explicit
    case 3:
        ...
        break;
    default:
        ...
        break;
}

For purposes of this question lets ignore the issue of whether or not fall-throughs are a good coding style.

Are there any languages that exist that allow fall-through and have made it explicit?

Are there any historical reasons that switch allows for implicit fall-through instead of explicit?

Best Answer

It's primarily historical, most languages just copied what C did.

The reason that C did it that way is that the creators of C intended switch statements to be easy to optimize into a jump table. This is also the reason that C limits switch statements to integral values.

In a jump table, the program will calculate what position to jump to based on the expression. The program will jump to that point and then continue executing from that point. If you want skip the rest of the table you have to include a jump to the end of the table. C uses explicit break statements so that there is a direct correspondence to this construct.