A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nested if...else
..if ladder.
Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.
The syntax of the switch statement
statement in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | switch (expression) { case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional . . . . case valueN: //code to be executed; break; //optional default: code to be executed if all cases are not matched; } |
The expression
is evaluated once and compared with the values of each case
label.
- If the expression and case value are matched then the corresponding code present within that particular case will be executed and a break statement is used to come out of the switch statement by skipping all of the other cases.
- If the values of expression and case do not match, the code within
default:
is executed.
Switch statement Flowchart:

Example of C++ switch statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | // C++ Program tocreate calculator #include <iostream> using namespace std; int main() { char choice; float num1, num2; cout << "Enter two numbers: " << endl; cin >> num1 >> num2; cout << "Enter one of the operator(+, -, *, /): "; cin >> choice; switch (choice) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break; case '*': cout << num1 << " *" << num2 << " = " << num1 * num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; default: //when entered operator does not match with any cases cout << "Entered operator is not correct"; break; } return 0; } |
Output:
1 2 3 4 | Enter two numbers: 2 3 Enter one of the operator(+, -, *, /): + 2 + 3 = 5 |
C++ nested switch Statement
The use of switch statement inside another switch statement is called nested switch statement.
Syntax of nested switch
statement in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | switch(ch1) { case 'A': printf("This A is part of outer switch" ); //use of another switch statement switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* case code */ } break; case 'B': /* case code */ } |
Example of C++ nested switch statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int a = 50; int b = 100; switch (a) { case 50: cout << "This is a outer switch" << endl; //another switch switch (b) { case 100: cout << "This is a inner switch" << endl; } } return 0; } |
Output:
1 2 | This is a outer switch This is a inner switch |