Last Updated:

Switch() Selection Operator in C++

There are cases when we have a need to make a check for something and, based on the result, make a certain action. For example, a calculator.

If you pressed "+", then add, clicked "-", then subtract and so on.

You can organize such logic through the if() selection statement. else


I think you have noticed that there is an asterisk in front of the variable znak, why is it?
It's not multiplication, it's pointer. Now do not ask yourself deeply what a pointer is, you will learn about it in detail a little later. In C++, working with symbolic variables is not an easy task. For example, double and single quotation marks are different things. To efficiently and correctly extract our symbols from the computer's memory, in this case, we need a pointer. Now it's just a necessary thing, nothing more.

This design already looks cumbersome, although we have only four options for action, and if there are ten options? What if twenty-five? It's going to be a nightmare design!

For this reason, the Switch selection operator was invented, where each action option is placed in a case container. This operator greatly simplifies the life of programmers.

Consider the same example with a calculator, but using a Switch.

In parentheses, after Switch, we specify the variable from which we should construct our conditions.
In the case, we specify with what we check our variable specified in switch.

break should be indicated at the end of the case container so that we do not have a check further. Now we have such a principle of operation of the algorithm: if the symbol is equal to '+', then add, if not equal, we look at whether the variable is equal to the symbol '', if not equal, we look if the variable is equal to the sign '*', yes, it is equal, then multiply the numbers and complete the check.

If we don't break, then the check will go all the way to the very end of our cases, and we don't need this, why ask the computer to compare something that we obviously know is not true?

Default() is required to take an action if no conditions in the case containers have been met

The design is much more understandable and beautiful. The principle of the algorithm is similar to the example of if().. else.

You can write anything to the case container and compare it to anything.


In this simple way, we got acquainted with the Switch() Choice Operator.