- The tested value can be interpreted as an integer (int, char or enum)
- The alternatives the value is tested are constants that can be interpreted as integers
The general form of the switch statement is:
switch ( tested_expression )
{
case alternative1:
statementlist1;
break;
.
.
.
case alternativeN:
statementlistN;
break;
default:
statementlist def;
break;
}
When the switch statement is executed, the tested expression is evaluated. It is compared to the alternatives one by one. If one of the alternatives matches the tested expression the execution begins in the corresponding statementlist i. The execution continues through the statementlist i until one of the following is reached:
- A break statement
- A return statement
- The end of the switch statement
The default clause can be omitted. If the value of the tested expression is not in the alternatives execution "falls through" the switch.
If one of the statementlist i's missing a break the execution continues from the next tested expression, otherwise continues from the statement following the switch.
This can be used in situations where several alternatives have same functionality:
switch( answer )
{
case 'n':
case 'N':
//the actions performed when
//the user answers n or N
break;
...
}
The break can also be omitted if the entire statement (or actually the function) is exited with return:
switch( month )
{
case 1:
return "January";
case 2:
return "February";
etc...
case 12:
return "December";
default:
return "Error";
}
Reference: msdn, intap, awitness
No comments:
Post a Comment