previous | index | next

The switch Statement

An alternative to nested if-else statements is C++'s switch statement.

If different courses of action are to be taken for different integer values, a switch statement is appropriate. Here is a comparison of switch and Racket's cond statement:

(define movie-rating
  (lambda (rating)
    (cond ((= rating 4)
           (display "Excellent"))
          ((= rating 3)
           (display "Good"))
          ((= rating 2)
           (display "Fair"))
          ((= rating 1)
           (display "Crappy"))
          (else
           (display "Invalid rating")))))
void movieRating(int rating) {
  switch (rating) {
  case 4: {
    cout << "Excellent";
    break;
  }
  case 3: {
    cout << "Good";
    break;
  }
  case 2: {
    cout << "Fair";
    break;
  }
  case 1: {
    cout << "Crappy";
    break;
  }
  default:
    cout << "Invalid rating";
  }
}

  • The expression after the switch keyword (rating in the example) must give an integer (or "scalar") value
  • Control then passes to the case clause corresponding to the integer value, whose code is executed
  • If the code for the matching case clause does not include a break statement, the code for the succeeding case clause is also executed
  • If the integer value does not match any case clause, the code for the default clause is executed

previous | index | next