Switch case statement
When we want
to solve multiple options types problem, for example menu base program, where
one is associated with each option and you need to choose only one value at a
time, then switch case statement is use.
Switch statement is a control statement that
allows us to choose only one choice among the many given choice. The expression
is switch evaluates to return an integral value, such then compare to the
values presents in different cases. It executes that block of code which match the
case value. If there is no match, then default block is executed. The general
form of switch case statements is as follows:
Syntax:
Switch(expression)
{
case
casevalue--1: block-1;
break;
case casevalue--2: block-2;
break;
case
casevalue --n: block-n;
break;
default :default-block;
}
- Rules for Switch case statement
- The switch expression must be an integral type.
- Case labels must be a constant or a constant expression.
- Case label must be unique no two labels can have the same value.
- Case labels must end with colon (:).
- The break statement transfers the control out of the switch statement.
- The break statement is optional i.e. two or more case labels may belong to the same statement.
- The default label is optional. If present, it will be executed when the expression does not find a matching case label.
- The default may be placed anywhere in the switch case statement but usually placed at the end.
- There can be 257 case labels in a switch case statement
1 Comments