Lesson 68 +10 XP

Switch Statements

Switch Statements

When you test one value against many possible values, a switch keeps the code tidy. It replaces a long chain of else ifs.

The shape

switch (expression) {
  case value1:
    // statements
    break;
  case value2:
    // statements
    break;
  default:
    // run when nothing matches
}
  • Evaluate expression once.
  • Compare it against each case value.
  • When a value matches, run its statements.
  • The break jumps out of the switch.
  • If nothing matched, default runs.

An example

#include <iostream>
using namespace std;

int main() {
  int day = 4;
  switch (day) {
    case 1:
      cout << "Monday" << endl;
      break;
    case 2:
      cout << "Tuesday" << endl;
      break;
    case 4:
      cout << "Thursday" << endl;
      break;
    default:
      cout << "Not a day I recognize" << endl;
  }
  return 0;
}

With day = 4, the case 4 matches and prints "Thursday".

When to use a switch

LearnCpp 8.5 says a switch is the natural fit when you test a single variable against several fixed constant values. It reads its labels at a glance. Compare one value to constants with a switch; here the if/else chain.

TL;DR

  • switch (expr) runs the matching case, then break ends the switch.
  • default runs when no case matched.
  • It is the cleanest way to compare one value against many constants.
  • Forgetting break makes the execution fall through to the next case.