C
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Arrays and Strings
-
Section 5: Pointers
-
Section 6: Memory Management
-
Section 7: Structures and Unions
-
Section 8: The Preprocessor and Build Process
-
Section 9: Standard Library: stdio.h
-
Section 10: Standard Library: stdlib.h
-
Section 11: Standard Library: string.h
-
Section 12: Standard Library: ctype.h and wctype.h
-
Section 13: Standard Library: math.h, complex.h, fenv.h, tgmath.h
-
Section 14: Standard Library: Type and Limit Headers
-
Section 15: Standard Library: Error Handling and Debugging
-
Section 16: Standard Library: Localization and Encoding
-
Section 17: Standard Library: time.h
-
Section 18: Standard Library: Concurrency (C11)
-
Section 19: POSIX and System Programming (unistd.h)
-
Section 20: More Data Structures
-
Section 21: Algorithms in C
-
Section 22: Bitwise Operations
-
Section 23: Command-Line Programs
-
Section 24: Debugging and Best Practices
-
Section 25: Compiler and Language Internals
-
Section 26: Embedded and Cross-Platform Considerations
-
Section 27: Networking Basics
-
Section 28: Practical Projects
-
Section 29: Interview Practice
-
Section 30: C23 Modern Features
-
Section 31: More Practice and Review
21: The switch Statement
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
switchstatement 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
defaultcase that tells the user "Invalid option, please try again." - Ensure that no "fall-through" occurs between the different menu options.
There are no comments for now.