Previous topic | Ada Home Page | Index

Case statements

A case statement is used for multiple selections

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:


Statement semantics


Selectors

A selector is a variable or expression resulting in a discrete value (INTEGER or CHARACTER)

The selector value_list may be:

Any number of when alternatives may be used

Restrictions on Case Statements

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


Case vs Multiple if

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

Multiple if

Use case whenever appropriate


Previous topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 13 Feb 96