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?
8
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.
3
Go allows explicit fallthrough using the fallthrough
keyword (break is implicit, but may be explicit):
switch val {
case 1: // breaks
case 2:
fallthrough
case 3:
goto
case 4, 5, 6: // equivalent to defining individual cases with explicit fallthough
break // unnecessary
default:
}
Here’s the relevant bit from effective go and the language spec.
I don’t think you can use goto
to go to a specific case, but you can make a label inside the case and use a goto
like normal.
As a bonus, Go lets you use binary expressions, strings, or types in a switch as case statements.
1