C ยท Chapter 13 of 45

C Switch Statement

The switch statement is an alternative to long if/else if chains when comparing one variable against many possible constant values. Each possible value is a case label.

Without a break statement, execution falls through to the next case, which is a common source of bugs, so remember to add break at the end of each case block.

Syntax
switch (expression) {
  case value1:
    // code
    break;
  default:
    // code
}

How switch works

The switch expression is evaluated once and compared against each case value in order. When a match is found, execution jumps there and continues until a break or the end of the switch.

The default case

The optional default case runs when no other case matches, similar to a final else in an if/else if chain.

Example 1 (c)
#include <stdio.h>

int main() {
  int day = 3;
  switch (day) {
    case 1: printf("Mon\n"); break;
    case 2: printf("Tue\n"); break;
    case 3: printf("Wed\n"); break;
    default: printf("Unknown\n");
  }
  return 0;
}
Output
Wed

day matches case 3, so 'Wed' is printed, and break stops fall-through.

Example 2 (c)
#include <stdio.h>

int main() {
  int x = 1;
  switch (x) {
    case 1:
    case 2:
      printf("One or Two\n");
      break;
    default:
      printf("Other\n");
  }
  return 0;
}
Output
One or Two

Grouping case 1 and case 2 without a break between them shares one code block.

Key points

  • switch compares one expression against multiple constant case values.
  • break prevents fall-through into the next case.
  • default runs when no case matches.
  • Case values must be integer or character constants.
๐Ÿ’ก Note: Forgetting break is a classic C bug โ€” always double-check every case unless fall-through is intentional.

๐Ÿ“ Quick Quiz

1. What happens if you omit break in a case?

2. What does the default case do?

3. What type of values can case labels use?