C++ Switch

C++ Switch Statement

Instead of writing many if..else if statements, you can use the switch statement to execute one of many code blocks.

How it Works

The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed.

Example

int day = 4;
switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  case 4:
    cout << "Thursday";
    break;
  default:
    cout << "Weekend!";
}
// Outputs: Thursday

The break and default Keywords


Exercise

?

Which keyword is used to stop the execution of more cases inside a switch statement?