Skip to Content
Course content

21: The switch Statement

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're standing in front of a vending machine. You don't walk up to the machine and ask, "Is this the Cola button? No. Is this the Sprite button? No. Is this the Water button? Yes!" That would be an exhausting way to get a drink. Instead, you just press the button for "B4," and the machine jumps directly to the mechanism that drops the item in slot B4. It doesn't care about the other buttons; it just cares about the one specific value you provided.

That's exactly how a switch statement works. While an if-else if chain is like walking down a line of doors and checking each one until you find the right one, a switch is like having a direct index. You give it a value, and it jumps straight to the matching "case."

Picking the right tool for the job

I'll be honest with you: you can do everything a switch does using if statements. But when you have one single variable that could be one of ten different values, a long chain of if-else if blocks becomes a nightmare to read. It looks cluttered. A switch statement tells anyone reading your code, "I am looking at one specific variable and reacting to its various possible values."

Here is how that looks in practice. Let's say we're building a simple menu for a game:

int choice = 2;

switch (choice) {
    case 1:
        printf("Starting new game...\n");
        break;
    case 2:
        printf("Loading saved game...\n");
        break;
    case 3:
        printf("Opening options menu...\n");
        break;
    default:
        printf("Invalid selection, try again.\n");
        break;
}

In this snippet, the program doesn't check case 1 if choice is 2. It jumps right to the case 2 label and executes the code there. I used an integer here, but keep in mind that switch works perfectly with char types too, since characters are just small integers under the hood in C.

The "Fall-Through" trap

You probably noticed that break statement at the end of every case. That is non-negotiable unless you're doing something very specific. If you forget the break, C does something called "falling through." It will execute the code for the matching case, and then it will keep executing every single case below it until it hits a break or the end of the switch.

Now, most of the time, falling through is a bug that will make you pull your hair out. But occasionally, it's actually useful. I use it when I want multiple inputs to trigger the same logic. For example, if we want both 'y' and 'Y' to mean "Yes":

char response = 'y';

switch (response) {
    case 'y':
    case 'Y':
        printf("You agreed!\n");
        break;
    case 'n':
    case 'N':
        printf("You declined.\n");
        break;
    default:
        printf("Please enter Y or N.\n");
        break;
}

See what happened there? I stacked case 'y' and case 'Y'. Since there's no break between them, both will lead to the "You agreed!" print statement. It's a clean way to handle aliases.

The safety net of the default case

The default label is your catch-all. It's like the "else" at the very end of a long chain. If the user enters something you didn't plan for—like entering 99 when your menu only goes up to 3—the default block handles it. I always recommend including one. Even if you think you've covered every possible value, adding a default case is a great way to catch unexpected behavior or handle errors gracefully.




📋 Practical Task

Build a Simple ATM Menu System

Your task is to write a program that simulates a basic ATM interface. The program should prompt the user to enter a number (1-4) to select an action from the following menu:

  • 1: Check Balance
  • 2: Deposit Funds
  • 3: Withdraw Funds
  • 4: Exit

Requirements:

  • Use a switch statement to handle the user's choice.
  • Each valid choice (1-4) should print a unique message (e.g., "Your balance is $1,000").
  • Include a default case that tells the user "Invalid option, please try again."
  • Ensure that no "fall-through" occurs between the different menu options.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.