The switch statement performs a multiway branch, useful when all branches of a conditional statement depend on the same variable. In this case, it is cumbersome to check the value of the same variable repeatedly using multiple if statements. The switch statement uses the following syntax to do the same thing more efficiently:
switch(variable)
{
case value_1:
statements
break;
case value_2:
statements
break
...
case value_n:
statements
break
default:
statements
break
}
The switch statement executes the code within the case statement that matches the current value of variable. If there is no match, the switch statement executes the default code or skips to the next statement if there is no default code. The break statements optionally delimit one case block of code from the next case. In the absence of a break statement, execution falls from one case to the next. This is a legal action, so be careful not to omit a break statement unless you actually intend for execution to fall through to the next case statement.
|
Copyright © 2014 CA.
All rights reserved.
|
|