3.5 case Statements

[ Table of Contents ] Prev ] Chapter Overview ] Next ] [ Glossary/Index ]

Case statements provide an alternative (to if statements) as a way of building conditional algorithms. They are compound statements that always include the reserved words or combinations: case , is, and end case. They also include at least two instances of the reserved word when and the symbol =>, and often include the reserved word others.

General Form

case expression is
  when choice_list_1 =>
      -- statement_Sequence_1;
  when choice_list_2 =>
      -- statement_Sequence_2;
  -- etc
  when others =>
      -- statement_Sequence_N;
end case; 

The expression in the first line of a case statement is of some discrete type and the various choices in the choice_lists must be of that same discrete type. The when others alternative, if present, must be the final one. The when others alternative must be included if the preceding alternatives do not exhaust all possible values of the discrete type.

In the example given below "when others =>" could be replaced by "when Oct | Nov | Dec =>" because all 12 month-abbreviation choices would then be covered.

Source Code Listing

------------------------------------------------------------------
--  This code fragment is a case statement used to determine which 
--  quarter of the year we are in. It is meant to be compared with 
--  (and could be substituted for) the third example 
--  (if-elsif-else statement) of the previous example.
------------------------------------------------------------------
  case Month_Abbreviation is
    when Jan | Feb | Mar =>
      Put_Line("We are in the first quarter.");
    when Apr | May | Jun =>
      Put_Line("We are in the second quarter.");
    when Jul | Aug | Sep =>
      Put_Line("We are in the third quarter.");
    when others =>
      Put_Line("We are in the fourth quarter.");
  end  case;
----------------------------------------------------------

Related Topics

3.4 if Statement A.2 Simple and Compound Statements

[ Back to top of pagePrev ] Next ]