Switch Statement in C

For Complete YouTube Video: Click Here

Here we will try to understand Switch Statement in C.

We have already covered if-else, Nested-if, and if-else-if Selection statements in c.

Switch Statement

A switch statement allows a variable to be tested for equality against a list of values.

Each value is called a case, and the variable being switched on is checked for each switch case.

We will try to understand the concept of switch statement by using an example in the image below.

Switch Statement in C
Switch Statement in C

In the above example, the grade is the variable whose value is checked for each case statement.

The value of grade is assigned B.

The compiler will check the value of the grade for each case in the switch statement.

If the value of grade is equal for any of the cases, then the compiler will execute the statements of that case.

In the above switch statement, the switch statement will execute the statements of case B.

The output of the switch is as shown in the image below.

Switch Statement in C Output Well Done
Switch Statement Output

The critical statement in every case is the break statement.

After executing all the case statements, the break statement will help to come out of the switch.

Switch Statement Without break

If the break statement is not provided in the case, the switch statement will execute the statements of the cases below it.

The image below is the program without the use of a break statement in the case.

Switch Statement in C without break
Switch Statement without break statement

The output of the above program is as shown below.

Switch Statement in C Output without break
Switch Statement in C Output without break

Switch Statement default case

In the above program, the last case of the switch statement is the default case.

If none of the cases are true, then the default case will get executed.

For example, if the grade’s value is X, the value of the grade is not equal to any of the cases.

In such cases, the default case will get executed.