UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

The switch structure

The switch structure can often be used in place of a cascade of if's.

Syntax

  switch (E) 
  {
      case C1 :
          statements_1;
          break;
      case C2 :
          statements_2;
          break;
      .
      .
      .
      default :
          statements_n;
          break;    
  }
  • E is the control expression which should evaluate to an integer.
  • the Ci's should be integer constants.
  • case C1: statements_1; break; is a case clause
  • default: statements_n; break; is a default clause

    Semantics

    1. E is evaluated
    2. If E's value is equal to one of the Ci's, then control is immediately transfered to that case.
    3. ...Otherwise, if there is a default clause, control is transferred there.
    4. ......Otherwise, exit the switch.
    5. The statements in that selected case are evaluated.
    6. If a break is evaluated, control is transfered to the next statement after the switch

    Good programming practice


    CSEE | 201 | 201 F'98 | lectures | news | help

    Wednesday, 16-Sep-1998 18:22:08 EDT