HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Switch Case

Definition:

The C++ Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. It is an alternative to the long if-else-if ladder which provides an easy way to dispatch execution to different parts of code based on the value of the expression.

Switch Statement


The switch statement in C++ is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. We can create different cases for different values of the switch expression. We can specify any number of cases in the switch statement but the case value can only be of type int or char.



Example:


    // C++ program to demonstrate syntax of switch 
    #include <iostream>
    using namespace std; 

    // Driver Code 
   int main() 
  { 
	  // switch variable 
	  char x = 'A'; 

	  // switch statements 
	  switch (x) { 
	    case 'A': 
		   cout << "Choise is A"; 
		   break; 
	    case 'B': 
		   cout << "Choise is B"; 
		   break; 
	    case 'C': 
		   cout << "Choise is C"; 
		   break; 
	    default: 
		   cout << "Choice other than A, B and C"; 
		   break; 
	} 
	return 0; 
  }

 

Output



Rules of the switch case statement in C++


There are some rules that we need to follow when using switch statements in C++.They are as follows:


  1. The case value must be either int or char type.

  2. There can be any number of cases.

  3. No duplicate case values are allowed.

  4. Each statement of the case can have a break statement.It is optional.

  5. The default Statement is also optional.

Working of the switch case statement in C++


The working of switch statement is as follows:


  1. Step 1: The switch expression is evaluated.

  2. Step 2: The evaluated value is then matched against the present case values.

  3. Step 3A: If the matching case value is found, that case block is executed.

  4. Step 3B: If the matching code is not found, then the default case block is executed if present.

  5. Step 4A: If the break keyword is present in the block, then program control comes out of the switch statement.

  6. Step 4B: If the break keyword is not present, then all the cases after the matching case are executed.

  7. Step 5: Statements after the switch statement is executed.