Skip to content
FollowtheDamnCode

switch

Picking one case out of many.

5 minute read

Big idea

switch jumps to the case that matches a value — a tidy replacement for a long else if chain that compares one variable against fixed numbers or characters.

The idea

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    default:
        printf("Some other day\n");
}
  • switch (day) — the value to match.
  • case 1: — "if day is 1, start here".
  • break; — "stop here and leave the switch".
  • default: — runs when no case matches, like a final else.

case labels must be constants — case 1: or case 'y':, never case x: or case n > 5:. For ranges and comparisons, use else if.

Don't forget break

Without break, C doesn't stop at the end of a case — it falls through into the next case's code too:

Fix the bug: day 2 should print only Tuesday
#include <stdio.h>

int main(void) {
    int day = 2;
    switch (day) {
        case 1:
            printf("Monday\n");
        case 2:
            printf("Tuesday\n");
        case 3:
            printf("Wednesday\n");
        default:
            printf("Another day\n");
    }
    return 0;
}
output
Tuesday

Run and edit it in the app.

Fall-through on purpose

Sometimes several values should do the same thing. Stack the labels:

Vowel or consonant — type a lowercase letter
#include <stdio.h>

int main(void) {
    char c;
    scanf(" %c", &c);
    switch (c) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("%c is a vowel\n", c);
            break;
        default:
            printf("%c is a consonant\n", c);
    }
    return 0;
}
input
e
output
e is a vowel

Run and edit it in the app.

Watch it

Think of it like

A vending machine: you press B3 and it goes straight to slot B3. It doesn't ask every slot in turn whether it's the one.

🕷️ Spidey-sense: Police-scanner codes. case 211: robbery, case 459: burglary, default: probably Jameson yelling. And always break — or I'll respond to every call after the first.

Key terms

  • case — A label for one value to match.
  • break — Leaves the switch (or a loop) immediately.
  • Fall-through — Running on into the next case because there was no break.
  • default — The case that runs when nothing else matches.

Check yourself

What happens if a case has no break?

When does default run?

Which is a valid case label?