Switch statements in C++

“switch” is a case control structure.

 It contains case and default values.

“switch” statement takes a value as a expression for equality testing against a list of values/case.

syntax for a switch statement:-

Rules of switch statement −

In a “switch” statement we can have any number of case.

for equality testing against a list of values/case, constant-expression for a case must be the same data type as the variable in the switch expression.

When “switch” expression value is equal to a case, the statements following that case will execute until a break statement is reached/executes.

When a break statement is reached/executes, the switch statement terminates, and the control jumps to the outside of switch.

break is a optional. If there is no break in the switch case, the flow of control will jump to the next case of switch until a break is reached.

switch statement also have a default case, which appear at the end of the switch. when none of the cases is true  then default case will execute. No break is needed in the default case. “default” case is also an optional.

Example: Write a program to  take one numbers from user between 1 to 3. Write entered number in words if number between 1 to 3 otherwise print wrong number using switch.

Output

Note: In the above program, output depends on user input

Example: Write a program using switch statement but without break.  

Output

Description: Because if there is no break in the switch case, the flow of control will jump to the next case of switch until a break is reached.

Note: In the above program, for example value of char variable c = ‘ A’ then the output will be as follows:

Output

Nested switch statements

In C++  programming language we can define switch statement within another switch.

Syntax for a nested switch statement: −

Categories C++