prev

Selection - Switch

next

switch statements evaluate an expression and then jump to the correct case element. This can be done with multiple if-else statements but for many branches a switch is generally easier to read. Formally,
  switch ( expression ) {
    case const-expr: statements;
    case const-expr: statements;
    default: statements;
  }
Example:
  switch ( var ) {

    /*
     * when var = 1 go here
     */
    case ( 1 ):
      printf ( "Got 1\n" );
      break;

    /*
     * when var = 2 go here
     */
    case ( 2 ):
      printf ( "Got 2\n" );
      break;

    /*
     * otherwise go here
     */
    default:
      printf ( "default clause\n" );
      break;
  }