Why do most languages still require breaks in a switch statement? Is Swift the beginning of the end for these break statements?
Context
Section titled: Context- In lab this week, we were tasked researching and experimenting with various features of the Swift language. One feature I particularly liked, was how Swift structures
switchstatements. Specifically, I think it is fantastic that Swiftswitchstatements do not fall through the bottom of each case and into the next one by default. Instead, the entireswitchstatement finishes its execution as soon as the first matching case is completed, without requiring an explicit break statement. - After seeing Swift’s brilliant
switchstatement design, I began thinking about a question that I’ve had since I was first introduced toswitchstatements in SE 1011; why do we require the programmer to insert an implicitbreakstatement inside of every case?
Research
Section titled: Research- The consensus of the community seems to be that we still use
breakbecause that’s the way it was done in C and the designers of new languages always want their syntax to be easily understood by programmers who are comfortable with this C-like syntax. - According to a popular answer on this stack exchange article, C was designed that way likely because of its concept as “portable assembly”. The C
switchstatement is basically an abstraction of a branch table, which has implicit fall-through. - The C#
switchstatement is interesting because it requires that explicit flow control (break,goto,returnorthrow) occur at the end of a case and will throw a compile time error if that flow control is omitted. Fall-through can be achieved only by using an explicitgotoat the end of a case. MSDN says the reason for this is that although “implicit fall-through behavior is often used to reduce the amount of code needed”, “as code moves from the initial development phase into a maintenance phase, [implicit fall-through] can lead to subtle errors that are very hard to debug”. - This Wikipedia article points out that many languages in the Pascal family also only execute the matching block, so this isn’t a new idea.
- In trying to find an answer for the fate of
break(or other control flow) inswitchstatements, I looked into several up and coming languages to see how they implementedswitchstatements.- Dart, Google’s new “replacement” for Javascript, took a page out of C#‘s book and throws an error if the control flow is omitted.
- D, which was recently adopted by Facebook as a C++ replacement, also throws an error for any but the final case.
- Go, another Google backed language written expressly for the cloud, does not require a control flow statement.
- Although the
breakinswitchstatements is not universal, it appears as though it will still be around for years to come.
Status
Section titled: Status- Question is mostly resolved, though a concrete answer is likely not available.
