Course contentsShow
← C
Lesson 265 of 1,2194. Control FlowFree lesson

Switch statement best practices

Switch statement best practices

What you'll learn: How to write clean, predictable switch blocks by using default cases and intentional break statements.

The safety net: Always use a default

Imagine you are at a vending machine. You press button 1 for water, 2 for juice, and 3 for soda. But what happens if you press button 9? A well-designed machine shouldn't just freeze; it should show an error message like "Invalid Selection."

In C, the default case is your "Invalid Selection" message. Even if you think you’ve covered every possible value, an unexpected number might sneak into your variable due to a bug elsewhere in your code. Without a default case, the program simply skips the entire block, leaving you wondering why nothing happened. Always include it as the final clause to catch the "unknowns."

Don't slip: The break rule

Think of a switch statement like a series of rooms connected by trapdoors. When the program finds a case that matches, it enters that room. However, unless you explicitly tell it to stop, it will fall through the floor into the next room, executing that code too! This is called "fall-through."

To prevent this, we use the break keyword. A break acts like a "Stop" sign, telling C to exit the switch block immediately after finishing the relevant code.

Putting it together

Here is how a professional, readable switch statement looks:

#include <stdio.h>

int main() {
    int diceRoll = 7; // An unexpected value

    switch (diceRoll) {
        case 1:
            printf("You rolled a one!\n");
            break;
        case 6:
            printf("Max score!\n");
            break;
        // The safety net
        default:
            printf("Invalid roll detected.\n");
            break; 
    }

    return 0;
}

Organizing for readability

To keep your code clean, keep the logic inside each case short. If you need to do ten different things for one case, it is usually better to put that logic in a separate function. Also, always place your default case at the very bottom. This follows the natural logic of "check these specific options first, then handle everything else last."

Key takeaway

Always include a break to prevent accidental fall-through and a default case to handle unexpected values.