Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases).
Switch case statements follow a selection-control mechanism and allow a value to change control of execution. They are a substitute for long if statements that compare a variable to several integral values. The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. In C++, the switch statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder.
Switch statement consists of conditional based cases and a default case.
In a switch statement, the “case value” can be of “char” and “int” type. Following are some of the rules while using the switch statement:
- There can be one or N numbers of cases.
- The values in the case must be unique.
- Each statement of the case can have a break statement. It is optional.