Intentional Fall-Through in Switch Statements
Some languages can continue from a matching case into following case bodies unless control leaves the switch.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace fall-through in C
Suppose case 1 records action A and case 2 records action B, with a break only at the end of case 2. A selector of 1 records A then B. A selector of 2 records B. This differs from an exclusive conditional chain.
State when it is desired
Several case labels can intentionally share one action by placing the labels together. If distinct bodies share later work, explicit common code can make the action sequence clearer. Preserve the observed behavior with inputs designed to distinguish cases.[1]
Work through the order in a C-style switch
Imagine a switch with case one appending a detail label and case two appending a common label. If case one does not leave the switch before case two's body, selecting one can append detail followed by common. Selecting two appends common alone. Write the observed operations in order before adapting the code. A reader accustomed to exclusive conditional chains can otherwise assume only one case body executes.
Choose a structure that keeps the shared action visible
Several labels can deliberately share one action using the language's documented syntax. If one case adds extra behavior and then performs a required common action, a helper used explicitly from both cases can make that relationship easier to inspect. The best choice depends on how much shared work there is and the compiler's diagnostics for fall-through.
Test each supported selector, including a selector matching no case if that is possible. Use different labels so the sequence is observable. If adding a new case changes where a prior case falls through, compare the result under the output and effects contract before deciding whether to preserve the old path.