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

Languages Where Omitting break Is a Compile Error

Languages That Require Explicit Fall-Through Syntax

Languages With switch-Like Syntax but No Fall-Through

Languages Without a switch Equivalent

Languages Where All Matching Blocks Execute

Every language handles this differently — quite educational!