Basic switch syntax and cases
What you'll learn: How to use the switch statement to choose one specific block of code to run based on a single integer value.
The "Shortcut" for If-Else
Imagine you are at a vending machine. You don't ask the machine, "Is this button 1? No? Is it button 2? No? Is it button 3?" Instead, you press a button, and the machine immediately identifies that specific choice.
In C, the switch statement works exactly like that vending machine. When you have one variable that could be several different fixed values (like 1, 2, or 3), a switch is much cleaner and easier to read than a long chain of if-else if statements.
Anatomy of a Switch
A switch evaluates an expression once and then looks for a matching case. Think of a case as a labeled landing pad for your code.
#include <stdio.h>
int main() {
int gear = 2;
switch (gear) {
case 1:
printf("Low power, high torque.\n");
break;
case 2:
printf("Cruising speed.\n");
break;
case 3:
printf("Maximum speed!\n");
break;
default:
printf("Invalid gear.\n");
}
return 0;
}
How it works
- The Expression: Inside
switch(gear), C looks at the value stored in the variable. - The Cases: It jumps directly to the
casethat matches that value. Ifgearis 2, it skips case 1 and goes straight to case 2. - The Break: This is vital. The
breakkeyword tells C, "Okay, we're done here, exit the switch." Without it, the code would keep running into the next case (this is called "fall-through"). - The Default: The
defaultkeyword acts like anelse. It catches anything that doesn't match the specific cases you listed. It’s your safety net.
Why use it?
While you could use a series of if statements, the switch tells anyone reading your code: "I am looking for one specific value among these known constants." It makes your logic organized, readable, and slightly more efficient for the computer to process.
Key takeaway
Use switch to jump directly to a specific code block based on a matching value, always ending each case with break to stop the execution.