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.

About author

33+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux and some other operating systems. Dr. Yilmaz Yoru was born in 1974, Eskisehir-Turkey. He graduated from the department of Mechanical Engineering of Eskisehir Osmangazi University in 1997. One year later he started to work in the same university as an assistant. He received his MSc and PhD degrees from the same department of the same university. He has married and he is a father of a son. Some of his interests are Programming, Thermodynamics, Fluid Mechanics and Artificial Intelligence. He also likes the graphical 2D & 3D design and high-end innovations.
Related posts
C++C++11C++14C++17Introduction to C++

Learn about Declaration of a Default Constructor Inside of Class Definition

Artificial Intelligence TechC++Learn C++

AI Tech :: Class Based Artificial Neuron Model in C++

Artificial Intelligence TechC++Learn C++

AI Techs :: Array Based Simple Artificial Neuron Model in C++

Artificial Intelligence TechC++Learn C++

AI Tech :: Structure Based Simple Artificial Neuron Model in C++

Worth reading...
Learn To Use Break And Continue In Loops With C++
en_USEnglish