- 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 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.
- After seeing Swift’s brilliant
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?
- 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 (
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”.
- 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) in
switchstatements, I looked into several up and coming languages to see how they implemented
- 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
switchstatements is not universal, it appears as though it will still be around for years to come.
- Question is mostly resolved, though a concrete answer is likely not available.