What is the switch Statement?
This is a different form of the multi way decision that It is well structured, but can only be used in certain cases where:
1. Here, Only one variable is tested, all branches must depend on the value of that variable. The variable should be an integral type. (int, long, short or char).
2. Every possible value of the variable can control a single branc and a final, catch all, default branch may optionally be used to trap all unspecified cases.
The universal form of switch statement is
switch(variable name)
{
case constant 1 : {
block 1;
break;
}
case constant 2 : {
block 1;
break;
}
.................
.................
default : {
default block;
break;
}
}
The switch statement tests the value of a variable name against a list of integer or character constants When a match is found the statements corresponding to that constant are executed and The switch differs from the if - else, as switch can only test for equality whereas if - else can do any type of relational & logical condition checking. Note that a body of the switch statement is a compound statement and the expression must evaluate to an integertype.
Once the expression is calculated, the control jumps to the appropriate case label and the statements corresponding to that case is executed until the break statement is reached and the break statement is used as an exit from the switch statement, otherwise the following case statements will get executed. If not any of the case matches, the control goes to the default statement and that particular statement gets executed.