C++ Switch Statement
The switch statement allows a variable to be checked for equality against a list of values that are defined in the code.
Each value is defined as the case, and the variable being switched is checked for each switch case.

Syntax:-
switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have N number of case statements */ default : /* Optional */ statement(s); /* If the above case matched or not. Default case always to be executed. */ }
Example:-
#include using namespace std; int main(){ int a=0; cout << "Enter the value of a:"; cin >> a; switch(a){ case 0: cout << "value is zero"; break; case 1: cout << "value is one"; break; case 100: cout << "value is hundred"; break; default: cout << "value is not 10, 50 or 100"; } return 0; }
Nested Switch Statement:-
Nested Switch Statement is used switch statement inside another switch.
Example:-
#include using namespace std; int main(){ int a=0; cout << "Enter the value of a:"; cin >> a; switch(a){ case 0: cout << "value is zero"; break; case 1: cout << "value is one"; break; case 100: cout << "value is hundred"; break; default: cout << "value is not 10, 50 or 100"; } return 0; }
Rules in switch statements
- Only one case is selected per execution for the switch statement.
- The value of expression identifies which case is selected.
- The expression must evaluate to byte, short, char, or int primitive data, a String, or a few other types.
- The type of expression and the type of the labels must be agreed.
- Each label shall be an integer literal (as 0, 23, or 'A'), a String literal (like "green"), but not an expression or variable.
- May have any number of statements in one statement List.
- The statement List is usually followed by the break;
- Switch case should have at most one default label.
- If no case label matches the value of the expression, then the default case will be picked, and then statements execute.
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.