Site icon Learn C++

Discover Switch Statements in C++

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,

[crayon-6606693376a94864570336/]

in each case you must start with case <number>: and end with break;

[crayon-6606693376a99830198857/]

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.

[crayon-6606693376a9b611002120/]

Here, we can also add all other numbers with default: case statement as given below.

[crayon-6606693376a9e551684681/]

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;

Get started building powerful apps with C++Builder!

Exit mobile version