Lesson 54 +10 XP

switch Statements

switch Statements

When you compare one value against many exact options, a switch is cleaner than a long if/else ladder.

The basic form

int day = 4;

switch (day) {
    case 1:
        printf("Monday");
        break;
    case 2:
        printf("Tuesday");
        break;
    case 3:
        printf("Wednesday");
        break;
    default:
        printf("Looking forward to the weekend");
}

Key parts

  • switch (value) - the value being checked.
  • case N: - a possible value to match.
  • break; - stops the switch once a case runs.
  • default: - runs when no case matches.

Why break?

Without break, execution falls through into the next case. That is rarely what you want.

TL;DR

  • switch tests one value against exact cases.
  • Each case usually ends with break;.
  • default catches everything unmatched.
  • Use switch for many exact comparisons on one value.