It is a multiway branch statement. It provides easy way to divert execution to different parts of our code based on value of an expression. It is often better alternative to large if-else-if chain.
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
If a case value matches with the given switch expression then it is executed and
break; statement is used to jump out of the switch block.
Knowledge2life 2
Note: Case statements are evaluated and executed in order they are written, starting from the first matched case value. Therefore, if we do not mention break; statement all the subsequent case statements will get executed until the break statement is found. To understand this scenario.
Let's look into following program to understand above point.
Default: Knowledge2life!
|