Switch case with multiple values in one case (C, C++, Java)
Codemia Knowledge Hub ·
To handle two values with one block in a switch in C, C++ or Java, stack the case labels with no code between them, like case 1: case 2:. Execution falls through from the first label to the next until it reaches a break or the end of the switch, so both values run the same code.
How a switch statement is structured
Unlike if-else, which evaluates boolean expressions, a switch picks the case that matches the value of an expression:
Sharing one block between two cases
Each case label is normally unique, but fall-through lets several labels share one block:
If num is 1 or 2, the program prints "Number is 1 or 2", without repeating the printf for each case.
This removes duplicated code when several inputs should produce the same result, and it groups related cases so the switch is easier to read and maintain.
Language support and fall-through risks
- Language support: fall-through behaves differently across languages. C and C++ support it implicitly. Python has no switch-case statement, so it needs other approaches such as dictionary mappings.
- Accidental fall-through: leaving out a
breakunintentionally sends execution into the next case and causes logic errors.
Typical uses
- Menu selections: several menu options that trigger the same action.
- State transitions: in finite state machines, different events that lead to the same transition.
| Feature | Description | Example Usage |
| Multiple Case Values | Multiple values triggering the same case logic. | Handling 1 and 2 as input |
| Fall-through Functionality | The lack of an immediate break allows execution flow to the next case.
It needs careful handling to avoid unintended execution flows. | Used distinctly in C/C++ |
| Code Reduction | Reduces redundancy and improves readability by avoiding repeated code. | Menu selections in GUI applications. |
Related reading
- Using variable in a LIMIT clause in MySQL
- Using vectors for performance improvement in Haskell
- Validation and Testing accuracy widely different
- Variadic nested loops
- var functionName = function() {} vs function functionName() {}
- vertical-align with Bootstrap 3
- Vectorizable implementation of complementary error function erfcf
- Vectorization of a function dependent on 2 arrays in numpy
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.