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

Comparing switch-case vs else-if ladders

Comparing switch-case vs else-if ladders

What you'll learn: When to choose a switch statement over a chain of if-else blocks for cleaner, faster code.

Up to this point, you have likely used if and else if to handle different conditions. While this works for every scenario, it can become messy when you are checking a single variable against many specific values. This is where the switch statement shines.

The Mental Model: The Hallway vs. The Elevator

Imagine you are looking for a specific room in a long hallway. An else-if ladder is like walking down the hall and knocking on every single door: "Is this Room 1? No. Is this Room 2? No. Is this Room 3?" You have to check every door until you find a match.

A switch statement is more like an elevator. You press the button for "Floor 3," and the system takes you directly there. You don't need to stop at Floor 1 or Floor 2 to see if they are the right one.

When to use which?

You should use an else-if ladder when your conditions are complex. For example, if you need to check ranges (e.g., age > 18 && age < 30) or compare different variables at once.

You should use a switch statement when you are comparing one single variable against a list of constant values (like integers or characters).

#include <stdio.h>

int main() {
    int gear = 2;

    // The Switch Approach: Clean and direct for fixed values
    switch (gear) {
        case 1:
            printf("High torque, low speed.\n");
            break;
        case 2:
            printf("Building momentum.\n");
            break;
        case 3:
            printf("Cruising speed.\n");
            break;
        default:
            printf("Invalid gear.\n");
    }

    return 0;
}

Readability and Performance

Beyond just looking cleaner, switch statements can be slightly faster. Because the compiler knows you are only checking one variable against constants, it can sometimes create a "jump table" to skip right to the correct case, rather than evaluating every condition one by one.

If you find yourself writing more than three else if statements to check the value of the same integer or character, it is usually time to switch to a switch.

Key takeaway

Use if-else for complex logic and ranges, but use switch for clean, direct jumps between specific constant values.