Programming
Switch Case Statement
Code Optimization
Javascript
Software Development

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:

c
1switch (expression) {
2  case constant1:
3    // code
4    break;
5  case constant2:
6    // code
7    break;
8  default:
9    // default code
10}

Sharing one block between two cases

Each case label is normally unique, but fall-through lets several labels share one block:

c
1int num = 2;
2switch (num) {
3  case 1:
4  case 2:
5    printf("Number is 1 or 2");
6    break;
7  case 3:
8    printf("Number is 3");
9    break;
10  default:
11    printf("Number is other than 1, 2, or 3");
12}

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 break unintentionally 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.
FeatureDescriptionExample Usage
Multiple Case ValuesMultiple values triggering the same case logic.Handling 1 and 2 as input
Fall-through FunctionalityThe 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 ReductionReduces redundancy and improves readability by avoiding repeated code.Menu selections in GUI applications.

Course
Intermediate
27 lessons
15 hours
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 course
Data 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.

Practice algorithms