DEV Community

Shoichi Okaniwa
Shoichi Okaniwa

Posted on • Originally published at qiita.com

I Encountered an Amazing switch Statement

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;
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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 break if a case block has no statements.
    • You can simulate fall-through using goto.

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 (case expression)
  • Scala (match expression)
  • Kotlin (when expression)

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 break to stop early.

Every language handles this differently — quite educational!

Top comments (0)