C++ Switch

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

A switch statement checks a variable against a list of case values. When it finds a match, it runs the code for that case. It is perfect for menus, day names, grades, and any situation with a fixed set of choices.

How switch works

You write switch followed by the variable in parentheses. Inside the braces, each case lists a possible value. The break keyword ends a case so the program jumps out of the switch. The optional default runs when no case matches.

A switch on the day of the week

#include <iostream>
using namespace std;

int main() {
  int day = 3;

  switch (day) {
    case 1:
      cout << "Monday\n";
      break;
    case 2:
      cout << "Tuesday\n";
      break;
    case 3:
      cout << "Wednesday\n";
      break;
    default:
      cout << "Another day\n";
  }
  return 0;
}
Note: The break keyword is very important. Without it, execution falls through into the next case and keeps running until it hits a break or the end of the switch.

The default case

The default case is like the else in an if chain. It catches any value that none of the cases matched. It is optional, but including it is good practice so your program always has a sensible response.

A simple menu with default

#include <iostream>
using namespace std;

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

  switch (choice) {
    case 'A':
      cout << "You chose Start.\n";
      break;
    case 'B':
      cout << "You chose Settings.\n";
      break;
    case 'C':
      cout << "You chose Quit.\n";
      break;
    default:
      cout << "Unknown option.\n";
  }
  return 0;
}

switch vs if...else

When to reach for a switch

Use switch whenUse if...else when
Comparing one variable to fixed valuesTesting ranges like x > 10
The value is an int or charConditions involve doubles or strings
There are many distinct casesThere are only one or two conditions
You want clean, readable branchingConditions combine with && or ||
Note: A switch can only test integer or character values, and each case must be a constant. If you need to compare ranges or use variables in your conditions, an if...else chain is the right choice.

Exercise: C++ Switch

Can a C++ switch statement use std::string values directly as case labels?