switch
Read · 1 of 4
Jump to the matching case
switch (x) jumps to the case whose value equals x, or to default if none match.
It then runs every line below until it meets break. Forgetting break makes it fall through into the next case.
Read this lesson as text
Pick one case out of many exact values, and why break matters.
Jump to the matching case
switch (x) jumps to the case whose value equals x, or to default if none match.
It then runs every line below until it meets break. Forgetting break makes it fall through into the next case.
The missing break
#include <stdio.h>
int main() {
int n = 2;
switch (n) {
case 1: printf("one\n");
case 2: printf("two\n");
case 3: printf("three\n"); break;
default: printf("other\n");
}
return 0;
}What does this print?
- two
- two three
- two three other
Show the answer
two three It jumps to case 2, prints two, falls into case 3 because there's no break, prints three, then stops at the break.
Exercise: Day of the week
Read a number 1 to 7 and print the day: 1 Monday … 7 Sunday. Anything else prints Invalid. Use switch.
Exercise: A tiny calculator
Read a number, an operator and another number, like 12 * 4, and print the result.
Support + - * / (whole-number division). For division by zero print Error.
Read the operator with scanf(" %c", &op): the space before %c skips spaces.