I Encountered an Amazing switch Statement
This article is a translated version of my original post on Qiita. Original (Japanese): https://qiita.com/segur/items/b11702d5360feeeab0f9
I Encountered an Amazing switch Statement
While working on a Java refactoring project, I came across this code:
switch ( cmd ) {
case 0:
// Process A
// fall through
case 1:
case 2:
// Process B
break;
default:
// Process C
break;
}
At first glance, case 0 looks like it only executes Process A. But look closely — there's no break after case 0, so it actually falls through and also executes Process B!
My first thought was that someone forgot to write break, but it turned out this was intentional behavior.
It's a Technique Called Fall-Through
Deliberately omitting break like this is called fall-through. And if you look at the comment in the code, it even says // fall through.
Replacing It with an if Statement
Fall-through is a clever technique, but it's easy to misread and can become a source of bugs. So, with some reluctance, I replaced it with an if statement:
if ( cmd == 0 ) {
// Process A
}
if ( cmd <= 2 ) {
// Process B
} else {
// Process C
}
Hmm — the original was actually simpler. It's a bit of a tradeoff. But at least there's no risk of misreading it now.
That said, if cmd were a String type, this kind of rewrite wouldn't work as cleanly. Tricky.
If you know a better way to write this, please let me know!
Fall-Through Support Across Languages
I got curious about how other languages handle this, so I did a quick survey.
Languages Where Omitting break Causes Fall-Through
- C
- C++
- JavaScript
- PHP
Languages Where Omitting break Is a Compile Error
- C#
- You can omit
breakif acaseblock has no statements. - You can simulate fall-through using
goto.
- You can omit
Languages That Require Explicit Fall-Through Syntax
- Perl (use
next) - Swift (use
fallthrough) - Go (use
fallthrough)
Languages With switch-Like Syntax but No Fall-Through
- Ruby (
caseexpression) - Scala (
matchexpression) - Kotlin (
whenexpression)
Languages Without a switch Equivalent
- Python
Languages Where All Matching Blocks Execute
- PowerShell
- Fall-through is not supported.
- All matching blocks are executed.
- You can use
breakto stop early.
Every language handles this differently — quite educational!