Saturday, September 5, 2009

switch statement

The switch statement can be used to implement a multi-alternative selection statement when:
  • 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
Note: The switch statement is not as general as the if statement. However, switch is more efficient in some situations.

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
If the tested expression doesn't match any of the alternatives the statementlist def is executed.

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

Previous post

Next post


No comments:

Post a Comment