C Switch
Switch Statement
Switch case statement evaluates a given expression and based on the evaluated value, it executes the statements associated with it. Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Following are some of the rules while using the switch statement:
- There can be one or N numbers of cases.
- The values in the case must be unique.
- Each statement of the case can have a break statement. It is optional.
switch(expression)
{
case value1: statement_1; break;
case value2: statement_2; break
.....
......
......
case value_n: statement_n; break;
default: default statement;
}
- The switch expression is evaluated once
- The value of the expression is compared with the values of each case
- If there is a match, the associated block of code is executed
- The break statement breaks out of the switch block and stops the execution
- The default statement is optional, and specifies some code to run if there is no case match
Some important keywords:
1) Break:
This keyword is used to stop the execution inside a switch block. It helps to terminate the switch block and break out of it.
2) Default:
This keyword is used to specify the set of statements to execute if there is no case match.