switch Statement

The nested if...else statement allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in nested if…else statement, it is better to use switch statement.

 

The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is cleaner and easy to understand.

Syntax

switch (n)
{
    case constant1:
        // code to be executed if n is equal to constant1;
        break;

    case constant2:
        // code to be executed if n is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if n doesn't match any constant
}

About switch Statement

When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.

In the above pseudo code, suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered.

The break statement is used to prevent the code running into the next case.

Flowchart Of switch Statement

switch_flowchart

Program On switch Statement

switch-program

Output

switch-output