Another one of the most used logical operators in C++ is switch() statement. A switch statement allows you to check variable and you can branch to different cases in accordance with it’s value. Each cases can be defined for different values, and the variable being switched on is checked for each case.
When the switch expression is evaluated once, the value of the given expression is compared with the values of each listed case. If it see there is a match, the associated block of code in that case statement is executed till the break. Default case is optional and can be defined at the end of case list. switch() used with a variable (generally it is an integer number) and the cases are grouped inside { } brackets, like this below,
1 2 3 4 5 6 |
switch(condition) { // list cases here } |
in each case you must start with case <number>: and end with break;
1 2 3 4 |
case <number>: break; |
For example, you can indicate condition of items by numbers, in this example below, we have 3 conditions Bad, Normal. Let’s set condition =3 and see how switch() function works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
int condition=3; switch(condition) { case 1: std::cout << "Bad"; break; case 2: std::cout << "Normal"; break; case 3: std::cout << "Good"; break; } |
Here, we can also add all other numbers with default: case statement as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
int condition=3; switch(condition) { case 1: std::cout << "Bad"; break; case 2: std::cout << "Normal"; break; case 3: std::cout << "Good"; break; default: std::cout << "Unknown"; break; } |
This code will output “Unknown” if the value of condition is 0 or below 0 or upper than 3. You can add many code lines between case and break;