Grouping multiple cases into one block
What you'll learn: How to handle multiple different input values with a single block of code by letting cases "fall through" to one another.
The "Shared Destination" Concept
In a standard switch statement, we usually end every case with a break to stop the code from running into the next section. However, sometimes different inputs should lead to the exact same result.
Think of a physical mailroom with several different slots for "Invoices," "Bills," and "Receipts." Even though the slots have different labels, they all drop the paper into the same "Accounting" bin. In C, we can mimic this by stacking case labels on top of each other without a break between them.
Stacked Cases
When you omit the code and the break for a case, C simply moves down to the next line of code it finds. This is often called "fall-through." By stacking labels, you are telling the computer: "If the variable matches A, B, or C, do this one thing."
Here is how you might handle a simple program that identifies if a day is a weekday or a weekend:
#include <stdio.h>
int main() {
int day = 6; // Let's say 6 is Saturday and 7 is Sunday
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("It is a weekday. Time to work!\n");
break;
case 6:
case 7:
printf("It is the weekend! Relax.\n");
break;
default:
printf("Invalid day code.\n");
}
return 0;
}
Why use this?
In the example above, we didn't have to write the printf and break five separate times for the weekdays. This makes your code much cleaner and easier to maintain. If you decide to change the message from "Time to work!" to "Keep grinding!", you only have to change it in one place instead of five.
Grouping is most effective when the logic for several inputs is identical. It keeps your control flow lean and prevents the "Wall of Code" effect that happens when you repeat yourself unnecessarily.
Key takeaway
Stack case labels without break statements to execute the same block of code for multiple different values.