C++Builder Discover Switch Statements in C++

FireWind

Moderator
Регистрация
2 Дек 2005
Сообщения
1,251
Реакции
887
Credits
212
Discover Switch Statements in C++
By Yilmaz Yoru April 7, 2021

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,
C++:
switch(condition)
{
 // list cases here
}
in each case you must start with case <number>: and end with break;
C++:
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.
C++:
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.
C++:
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;