Zach Posten - 2015 Mar 25
Why do most languages still require breaks in a switch statement? Is Swift the beginning of the end for these break statements?
switchstatements. Specifically, I think it is fantastic that Swift
switchstatements do not fall through the bottom of each case and into the next one by default. Instead, the entire
switchstatement finishes its execution as soon as the first matching case is completed, without requiring an explicit break statement.
switchstatement design, I began thinking about a question that I've had since I was first introduced to
switchstatements in SE 1011; why do we require the programmer to insert an implicit
breakstatement inside of every case?
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.
switchstatement is basically an abstraction of a branch table, which has implicit fall-through.
switchstatement is interesting because it requires that explicit flow control (
throw) 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 explicit
gotoat 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".
break(or other control flow) in
switchstatements, I looked into several up and coming languages to see how they implemented
switchstatements is not universal, it appears as though it will still be around for years to come.