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.
In the sample case statement above, if A contained 12, what would be executed?
|
|
|
|
|---|
David A. Wheeler (dwheeler@ida.org)