C++Introduction to C++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,

in each case you must start with case <number>: and end with 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.

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

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!

close

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++Introduction to C++Learn C++

Learn To Use Break And Continue In Loops With C++

C++Introduction to C++Learn C++

Learn To Define And Use Arrays In C++

C++Learn C++Videos

Learn C++ With Back to Basics: Design Pattern by Mike Shah (CPPCon 2020) Video

C++Introduction to C++Learn C++

Discover If Statements and Conditions in C++

Worth reading...
How To: Use Variables In C++ Programming
en_USEnglish