The Switch statement is used to execute one of many code statements. It can be considered as group of If-else statements.
switch (expression){ case 1: statement 1; break; case 2: statement 2; break; ... ... ... case N: statement N; break; default: default statement; }
The Switch expression is evaluated and matched with the cases. When Case matches, the following block of code is executed.
In the below example, the switch expression is a variable called i with value 2 which is matched against case values. When the case value matches with expression value, the following block of code is executed.
#include <iostream> using namespace std; int main (){ int i = 2; switch(i){ case 1: cout<<"Red\n"; break; case 2: cout<<"Blue\n"; break; case 3: cout<<"Green\n"; break; } return 0; }
Blue
Default case and break statement are optional here.
In the below example, the switch expression is a variable called i with value 10 which is matched against case values. When the case value matches with expression value, the following block of code is executed and there is no case with value 10, hence default block of code is executed.
#include <iostream> using namespace std; int main (){ int i = 10; switch(i){ case 1: cout<<"Red\n"; break; case 2: cout<<"Blue\n"; break; case 3: cout<<"Green\n"; break; default: cout<<"There is no match in the switch statement.\n"; } return 0; }
There is no match in the switch statement.