The default case for unhandled values
What you'll learn: How to use the default keyword as a safety net for values that don't match any specific case in your switch statement.
The catch-all bucket
Imagine you are sorting fruit into bins. You have a bin for apples, a bin for bananas, and a bin for cherries. But what happens when someone hands you a dragonfruit? If you only have bins for those three specific fruits, you won't know where to put the outlier.
In C, the switch statement works the same way. While case labels handle specific values, the default keyword acts like a "catch-all" bucket. It handles every situation you didn't explicitly plan for. Without it, if a variable doesn't match any case, the program simply skips the entire block and moves on, which can lead to confusing bugs where "nothing happens."
Using the default keyword
The default case is usually placed at the very end of the switch block. It doesn't need a specific value next to it because it automatically triggers if all other cases fail. It serves as a great place to put error messages or fallback logic.
#include <stdio.h>
int main() {
int gear = 5;
switch (gear) {
case 1:
printf("Low power, high torque.\n");
break;
case 2:
printf("Gaining speed.\n");
break;
case 3:
printf("Cruising speed.\n");
break;
default:
// This runs if gear is anything other than 1, 2, or 3
printf("Invalid gear! Please select 1, 2, or 3.\n");
break;
}
return 0;
}
Why it matters
Think of default as your "Plan B." In professional programming, it is considered best practice to include a default case even if you think you’ve covered every possibility.
If you are building a menu for a game (1 to Start, 2 to Quit) and the user accidentally presses 7, the default case allows you to tell them, "Invalid choice," rather than leaving the user staring at a frozen screen. It makes your code more robust and user-friendly by ensuring that your program always has a response, no matter what data it receives.
Key takeaway
The default case is an optional but essential safety net that executes code when no other case matches the input.