C++ switch statement
- switch-case statement is a multi-way branch statement.
- case statement enables the user to choose a option from a number of options.
- The switch statement requires only one argument/expression of any data type which is checked with the case constants. If the value of expression is matches with any case constant then that particular case statement is executed, If the value of expression does not match with any case constant then default block is executed.
- The break statement is used to exit from the current case block.
- switch statement is alternate of if else ladder statements.
- In switch case, default is the optional part if we don’t want to use then program will run smoothly without any error.
- Here is the syntax of switch-case statement:
case constant A:
case constant B:
- According to the above syntax if the expression matches with the case constant A then the statements present inside case constant A block will be executed, if the expression matches with the case constant B then the statements present inside case constant B block will be executed and if expression does not match with any of the case constants then the statement present inside the default block will be executed. Here is the diagram that shows the concept of switch-case statement:
- Here is an example of switch-case statement as follows:
cout<<“n Enter your choice:”;
cout<<“nYour choice is 1”;
cout<<“nYour choice is 2”;
cout<<“nYour choice is 3”;
cout<<“nNo match found”;
The output of the above program is as follows:
Enter your choice: 3
Your choice is 3