C++ switch Statement

In this lesson, you will learn about the switch Statment in C++, its usage, along with examples to better understand the topic.

switch Statement in C++ explained

A switch statement is used when you have too many conditions to evaluate—having too many ‘if‘ conditions can increase your code’s complexity. Thus, the switch statement is the way to go; it’s simpler to read, elegant, and produces cleaner code.

Syntax of switch Statement in C++

switch (expression)  {
    case 1:
        // code to be executed if  expression is equal to 1;
        break;

    case 2:
        // code to be executed if expression is equal to 2;
        break;
        .
        .
        .
        case n:
        // code to be executed if expression is equal to n;
        break;

        
    default:
        // code to exected if the expression does not match with any cases above
}

In a switch statement, the expression is checked against the value of each case label. In the syntax above, if the expression is equal to 1, the case that has the label ‘1’ is executed. The Break statement tells the compiler to exit the statement.

Flowchart

Example of switch Statment in C++

#include <iostream>

using namespace std;

int main() {
  int num;
  cout << "Enter a number: " << endl;
  std::cin >> num;

  switch (num) {
  case 1:
    cout << "You entered 'One'" << endl;
    break;
  case 2:
    cout << "You entered 'Two'" << endl;
    break;
  case 3:
    cout << "You entered 'Three'" << endl;
    break;
  case 4:
    cout << "You entered 'Four'" << endl;
    break;
  case 5:
    cout << "You entered 'Five'" << endl;
    break;
  default:
    cout << "You entered  " << num << endl;
  }

  return 0;
}

Output

Enter a number:

5

You entered ‘Five’

Points to remember

  • switch statements are useful if you have too many conditions to evaluate.
  • The break statement is used to exit a switch statement.

 

Back to: Learn C++ Programming > Control Statements in C++

Leave a Reply

Your email address will not be published. Required fields are marked *