c-plus-plus
  1. c-plus-plus-switch

C++ Control Statement Switch

The switch statement is used to execute different actions based on different conditions. It is similar to the if-else statement, but the switch statement provides more readability and simplicity.

Syntax

The syntax of the switch statement is as follows:

switch(expression){
    case constant-expression: 
        statement(s);
        break; // optional
    case constant-expression:
        statement(s);
        break; // optional
    // you can have any number of case statements
    default : // Optional
        statement(s);        
}

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

Example

#include <iostream>
using namespace std;

int main() {
   int day = 3;
   
   switch(day) {
      case 1 :
         cout << "Monday" << endl; 
         break;
      case 2 :
         cout << "Tuesday" << endl; 
         break;
      case 3 :
         cout << "Wednesday" << endl; 
         break;
      case 4 :
         cout << "Thursday" << endl; 
         break;
      case 5 :
         cout << "Friday" << endl; 
         break;
      case 6 :
         cout << "" << endl; 
         break;
      case 7 :
         cout << "Sunday" << endl; 
         break;
      default :
         cout << "Invalid day" << endl;
   }
   
   return 0;
}

Output

Wednesday

Explanation

In the above example, we have a variable day which is set to 3. We have used a switch statement to check the value of day and print the corresponding day. As the value of day is 3, the case for day equal to 3 is executed, and the output is "Wednesday".

Use

The switch statement is widely used in C++ programming to control the flow of a program based on different conditions. It is often used in menus, games, and other applications where different options need to be executed based on different conditions.

Important Points

  • The switch statement can only be used with integers and characters.
  • Each case block must end with the break keyword to prevent fall-through to the next case.
  • The default block is optional and is executed if none of the cases match the value of the expression.
  • You can have any number of case statements in a switch statement.
  • The break keyword is used to exit a switch block.

Summary

  • The switch statement is used to execute different actions based on different conditions.
  • It provides more readability and simplicity than the if-else statement.
  • The syntax of the switch statement includes the switch keyword, an expression, case statements, and a default statement (optional).
  • The switch statement can only be used with integers and characters.
  • Each case block must end with the break keyword to prevent fall-through to the next case.
  • The default block is optional and is executed if none of the cases match the value of the expression.
Published on: