Learn C · lesson 15 of 60 · about 8 minutes
switch
Give the report commands: choose between exact values with switch, case, break and default, let cases share code, and read one letter safely.
What you'll learn
- Write a switch statement
- Use break to stop fall-through
- Handle everything else with default
Many exact matches
The report ends by asking for a command: c to clean up, r to restart, s to shut down. switch (cmd) compares the value with each case. A matching case runs until break, and default catches everything else.
switch works with whole numbers and chars, such as an int or a char, but not with strings.
Menu choices
#include <stdio.h>
int main(void) {
char choice = 'b';
switch (choice) {
case 'a':
printf("Start lesson\n");
break;
case 'b':
case 'B':
printf("Open shop\n");
break;
default:
printf("Unknown option\n");
}
return 0;
}Output
Open shopbreak and falling through
Without break, the program carries on into the next case's code. That's called falling through, it's usually a bug, and gcc warns about it. Cases with nothing between them are different: stacking them on purpose lets them share code, so case 'b': and case 'B': can run the same lines.
Reading one letter
scanf("%c", &cmd) reads the very next character, and after an earlier scanf("%d", ...) that's the newline left behind when the user pressed Enter. So cmd holds a newline, and the switch goes to default. A space before the %c, as in scanf(" %c", &cmd), skips spaces and newlines first, so cmd gets the letter.
Tip
switch only works with whole numbers and characters. For ranges like score >= 80, use if / else if.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.