"Switch" Statement in C++

"Switch" Statement in C++

The "switch statement" is used as a substitute of "nested-if-else" statements. It is used when multiple choices are given and one choice is to be selected.

The "nested-if-else" structure becomes complicated in multiple choices. The "switch" statement is used in such situations. Only one condition is given in the "switch statement" and multiple choices are given inside the main body as cases.

The "switch statement" evaluates an expression and returns a value. One of the choices or cases in the "switch statement"  is executed depending upon the value returned by the expression.The returned value is compared with the constant values given in the cases. If the returned value matches the case value, the statement under the case are executed.

The syntax of switch is:

switch (expression)
    {
            case const-1:
               statements;
                 break;
            case const-2:
               statement;
                 break;
             case const-n:
               statements;
                 break;
              default:
                statements;
    }


The const-1, const-2, etc are numeric constants or character constants.
      In the above syntax of the switch statement, one test expression appears with in the switch statement. The body of the switch statement  contains many cases.

   When the switch statement is executed, the given expression is first evaluated and then the value returned by the expression is compared with the values of constants given in each case. If the value matches with constant value of a case then the statements of that case are executed.

    Keyword default is also used in the body of switch statement. If no case is matched  then the statements  under the default are executed. Its use is optional. If it is not used then the control exits from the body of the switch statement and goes to the first statement following the end of the switch structure.
Creative Commons License
Pakistan How by Tahira Aijaz is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.