C Switch

When you need to compare one variable against many possible fixed values, a long chain of else if statements can get messy. The switch statement offers a cleaner way to pick one block of code to run based on the value of a single expression.

How switch works

A switch takes an expression and compares it to a list of case labels. When it finds a matching case, it starts running the code from there. The break keyword stops the switch so it does not fall through into the next case.

Day of the week

#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        default:
            printf("Another day\n");
    }
    return 0;
}

The break and default keywords

The break keyword ends the switch once a case has done its work. The default label is optional and runs when none of the cases match, similar to the else in an if...else chain.

  • case labels must be constant values, such as numbers or characters.
  • break stops the switch and jumps to the code after it.
  • default handles any value that no case matched.
  • The switch expression must be an integer type or a character.

Forgetting break: fall-through

If you leave out break, execution keeps going into the next case, even if it does not match. This is called fall-through. It is sometimes useful on purpose, but for beginners it is usually a bug, so remember your break statements.

Grouping cases on purpose

#include <stdio.h>

int main() {
    char grade = 'B';

    switch (grade) {
        case 'A':
        case 'B':
            printf("Well done!\n");
            break;
        case 'C':
            printf("You passed.\n");
            break;
        default:
            printf("Keep trying.\n");
    }
    return 0;
}
Note: Because 'A' and 'B' share the same code with no break between them, both grades print "Well done!". This intentional fall-through is a handy way to group cases.
PartPurpose
switch (expr)picks the value to test
case value:a label to match against expr
break;stops the switch
default:runs when no case matches

Exercise: C Switch

What kind of expression must a case label use in a switch statement?