Section 5.2 - Case Statements

Sometimes you want to execute one of many different sequences of statements, based on the value of a single expression. You can do this by using a set of "elsif" clauses, but most languages (including Ada) provide a simpler way to do this.

Ada's mechanism is a case statement. A case statement computes the value of an expression, and then compares it to lists of values to determine what to execute next. Here's an example:

  case A is                      -- Execute something depending on A's value:
    when 1          => Fly;      -- if A=1, execute Fly.
    when 3 .. 10    => Put(A);   -- if A is 3 through 10, put it to the screen.
    when 11 | 14    => null;     -- if A is 11 or 14, do nothing.
    when 2 | 20..30 => Swim;     -- if A is 2 or 20 through 30, execute Swim.
    when others     => Complain; -- if A is anything else, execute Complain.
  end case;

Note that after each "when" is a list of one or more possible values. A "when others" clause matches anything that hasn't matched anything else. A case statement chooses one and only one alternative; the alternatives must be exhaustive (cover all possible cases) and exclusive (you can't have two "when 5 =>" clauses). An Ada compiler will detect missing or duplicate cases at compile-time.

Here's the full BNF for the case statement:

case_statement ::=
  "case" expression "is"
      case_statement_alternative
     {case_statement_alternative}
  "end case;"

case_statement_alternative ::=
   "when" discrete_choice_list "=>" sequence_of_statements

discrete_choice_list ::= discrete_choice { | discrete_choice }

discrete_choice ::= expression | discrete_range | "others"

The Ada case statement is functionally identical to C's "switch" statement. Unlike C, Ada supports ranges of values and does not require a "break" statement at the end of each sequence (a common C error).

Case statements are useful, but a large number of case statements may indicate that you should be using a more object-oriented approach. Ada's object-oriented features will be discussed in a later lesson.


Quiz:

In the sample case statement above, if A contained 12, what would be executed?

  1. Fly.
  2. Put(A).
  3. null (do nothing).
  4. Swim.
  5. Complain.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 5 outline

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s5s2.htm".