next up previous contents
Next: Recursion Up: Handy but not Necessary Previous: for   Contents

case

The case statement is similar to the switch statement in C-based languages. This statement makes it easier for a program to examine a scaler value and determine what to do next.

A ``scalar'' value is either an integer or a character in Pascal. A case statement lists statements corresponding to specific values of the scalar value. For example, the following code prints a different message depending on the value of i*j-20:

case i*j-20 of
  2: writeln('two''s company');
  5: begin
       writeln('hawaii');
       writeln('five-oh')
     end;
  7: writeln('seven years in tibet');
  12: writeln('the dirty dozen');
  else
    writeln('I don''t know a movie with this number.');
end

This code prints a movie/series name based on the value of i*j-20. Note that if there is more than one statements for a particular value, you must use a block statement to encapsulate the statements. The else reserved word matches all values not listed explicitly as a ``catch all'' mechanism.

As powerful this statement may seem, it can be implemented by a series of if-then-else statements. The case statement also has limitations. For example, ``scalar'' values do not include string values. In addition, the values to match statements in a case statement must be constants.


Tak Auyeung 2003-12-03