Previous topic |
Ada Home Page |
Index
Case statements
A case statement is used for multiple selections
- alternative to multiple if
- used when can explicitly list all alternatives for one selector
An example program
shows the use of a case statement to classify characters.
Note that all possible characters are handled, and that
the selectors for each case are expressed in a variety of different ways.
A second example
shows the use of a case statement to classify operators
for a simple calculator.
Statement form
statement_before;
case selector is
when value_list_1 =>
statement(s)_1;
when value_list_2 =>
statement(s)_2;
...
when others =>
statement(s)_n;
end case;
statement_after;
Note preferred layout style:
- one level of indent for when value list
- second level of indent for statements associated with when
alternatives
Statement semantics
A selector is a variable or expression resulting in a discrete value
(INTEGER or CHARACTER)
The selector value_list may be:
- a single constant value, eg. 'a'
- a series of alternatives, eg. 'a' | 'b' | 'c'
- a range of values eg. 'a' .. 'z'
- or any combination of the above
Any number of when alternatives may be used
A particular value may only occur once in a case statement (whether
as a constant or part of a range)
All possible values of the selector must be supplied, either
explicitly or using when others.
when others indicates the action when none of the listed when
alternatives are matched
- it must be the last alternative
- to specify no action, use the "null;" statement.
Any selection implemented with case can also be implemented with if.
For example, the first
case statement example program,
which classifies characters, can easily be
rewritten using if statements.
Often the case implementation is shorter, cleaner, and more elegant.
Case
- table of values and actions
- easy to specify range of selector values
- easy to specify alternative selector values
Multiple if
- sequence of decisions and actions
- used when cannot specify range directly
- selector is not discrete
- choice depends on more than one selector
Use case whenever appropriate
Previous topic |
Ada Home Page |
Index
c-lokan@adfa.oz.au / 13 Feb 96