C++ Switch

C++ Switch


C++ Switch :

The switch statement used to specify many alternative blocks of code to be executed. In other words, The Switch statement is used to perform different actions based on different conditions like on or off.

The Syntax of Switch statement is as follows:

switch (expression)
{
   case condition1: // code to be executed if expression = condition 1;
        break;
    case condition2: // code to be executed if expression = condition 2;
        break;
    default: // code to be executed if expression doesn't match any cases
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case condition.

If there is a match, the corresponding code after the matching condition is executed. For example, if the value of the variable is equal to expression = 1, the code after expression = 2: is executed until the break statement is encountered.

If there is no match, the code after default: is executed.

Example :

Output :