Skip to main content

5.5) Switch Statement


A switch statement chooses a path based on the value of a char or integer variable:

switch (response) {
  case 1:
    cout << "You entered 1" << endl;
    break;
  case 2:
    cout << "You entered 2" << endl;
    break;
  default:
    cout << "You entered something else" << endl;
    break;
}

Key Points

  • It is not possible to switch on a floating-point variable or string
  • The case labels represent values for the switch variable; code following a case label will execute if the switch variable has the given value
  • break is needed to terminate a case and prevent 'fall-through' to subsequent cases
  • Use default for statements that should execute when no cases match