19.2.2.  Selection Statements

[ fromfile: controlstructures.xml id: condexpr ]

switch

switch(integralExpression) {
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
        ...
    case valuen:
        statementn;
        break;
    default:  
        defaultStatement;
}
nextStatement;
  if(integralExpression == value1)
     statement1;
  else if(integralExpression == value2)
     statement2;
  ...
  else if(integralExpression == valuen)
     statementn;
  else
     defaultStatement;
[Note]Note

Long compound conditional statements and switch statements should to be avoided in object-oriented programming (unless they are isolated in factory code) because they tend to make functions complex and hard to maintain.

If each case can be rewritten as a method of a different class, you can use the Strategy pattern (and the virtual table) instead of writing your own switch statement.



[77] case labels are not the same as goto labels, which are used as destinations for the infamous goto statement. goto labels must be identifiers. In particular, they cannot be integers.