C++ Switch Case Statement

In this lesson, We will learn about the Switch Statement in C++ and its functions with a few examples.


C++ Switch Case Statement

A switch case statement is a shortened version of the C++ Nested if-else statements, making it easier to avoid using a lengthy “if else” chain. We can choose one of several possible code blocks to run using the switch statement.

The C++ switch statement has the following syntax:

Basic Syntax

switch (expression) {
case value1:
  // statements
  break;
case value2:
  // statements
  break;
default:
  // statements
  break;
}

In the above syntax, each case label’s values are considered once the expression has been evaluated. The relevant code is run following the matching label if a match is found. For instance, if value2 is equal to the variable’s value, the code following case value2: is run until the break statement is reached.

If no match is found, the code following default is executed.

Note
It is possible to accomplish the same task using the if…else…if ladder. Nevertheless, the switch statement’s syntax is more straightforward and considerably simpler to comprehend and write.

Example

//A Program to build a season of the year
#include <iostream>

using namespace std;
int main() {
  int seasonOfYear;
  cout << "Enter your fav season and know it’s the month\nPress 1 for Winter\nPress 2 for Spring\nPress 3 for Summer\nPress 4 for Autumn\n ";
  cin >> seasonOfYear;
  switch (seasonOfYear) {
  case 1:
    cout << "\nDecember, January and February.";
    break;

  case 2:
    cout << "\nMarch, April and May.";
    break;

  case 3:
    cout << "\nJune, July and August.";
    break;

  case 4:
    cout << "\nSeptember, October and November.";
    break;

  default:
    cout << "\nInvalid Season.";
    break;

  }
  return 0;
}

Output

Enter your fav season and know it's the month
Press 1 for Winter
Press 2 for Spring
Press 3 for Summer
Press 4 for Autumn
4
September, October and November.

The program above takes the user input with the variable preceding program. Then it sends this variable as an expression to the following switch statement. The value of “seasonOfYear” is tested in various possibilities to determine which code block needs to be performed. If you enter 4, case 4 will be executed and will print:

September, October and November.

This concludes the C++ Switch Statement lesson. The next lesson will teach about the “for loop” in C++.