Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Basics and Types

Enumerations, Subranges and Sets in Pascal

Use Pascal's ordinal types: enumerations, subrange types, Ord, Succ, Pred, High and Low, set types with in, union and difference, and how sets map to bit flags.

Pascal lets you define your own simple types that describe a problem better than plain integers. A weekday is not just a number from 0 to 6; a percentage is not any integer; a collection of permissions is not an arbitrary bit pattern. Enumerations, subranges and sets express these ideas directly, and the compiler checks that you use them correctly.

All three are built on ordinal types: types whose values are in a fixed order and can be numbered. Integers, characters, booleans, enumerations and subranges are ordinal; reals and strings are not.

Pascal code is read-only; the C stand-ins at the end show how the same ideas look in memory.

Enumerated types

An enumeration lists the allowed values by name:

PASCAL
type
  TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  TColor = (Red, Green, Blue);

var
  today: TDay;
  paint: TColor;

begin
  today := Wed;
  paint := Blue;
  if today = Wed then
    WriteLn('Midweek');
  WriteLn(Ord(today));      { 2: numbering starts at 0 }
end.

The names are constants of that type. Because they are not numbers or strings, today := 3 is a compile error and paint := Mon is too. The compiler stops you from mixing unrelated things.

Operations on ordinals:

Function Result Example with TDay
Ord(x) Position, starting at 0 Ord(Wed) is 2
Succ(x) Next value Succ(Mon) is Tue
Pred(x) Previous value Pred(Fri) is Thu
Low(T) / High(T) First / last value High(TDay) is Sun
Inc(x), Dec(x) Step the variable

Enumerations work as loop counters and case selectors:

PASCAL
var
  d: TDay;
begin
  for d := Mon to Sun do
    Write(Ord(d), ' ');
  WriteLn;           { 0 1 2 3 4 5 6 }
end.

Calling Succ(Sun) is an error: there is nothing after the last value. To print the name of an enumeration value you need GetEnumName from TypInfo (needs run-time type information) or your own array of strings, as in Arrays: Static, Dynamic and Open.

You can give explicit numbers in Delphi and Free Pascal, (Low = 10, Mid = 20, High = 30), but then the type has gaps and loses some safety, so use it only when matching an external API.

Subrange types

A subrange is a limited slice of an ordinal type, written low..high:

PASCAL
type
  TPercent = 0..100;
  TLetter = 'A'..'Z';
  TWorkDay = Mon..Fri;     { subrange of an enumeration }

var
  score: TPercent;
begin
  score := 85;
  score := 150;            { compile error for a constant; run-time error with {$R+} }
end.

The compiler picks a size that fits the range (a 0..100 fits in a byte). With range checking on ({$R+}) assigning an out-of-range value is detected at run time, which turns many silent bugs into loud ones. Subranges also serve as array index types:

PASCAL
var
  hits: array[1..12] of Integer;     { 1..12 is a subrange index }

Sets

A set is an unordered collection of distinct values of one ordinal base type. Declare it with set of:

PASCAL
type
  TDaySet = set of TDay;
  TCharSet = set of Char;

var
  weekend, free: TDaySet;
  vowels: TCharSet;

begin
  weekend := [Sat, Sun];
  vowels := ['a', 'e', 'i', 'o', 'u'];
  free := weekend + [Fri];            { union }
  if Sat in free then
    WriteLn('Saturday is free');
  if 'e' in vowels then
    WriteLn('e is a vowel');
end.

A set literal uses square brackets and may contain ranges: ['0'..'9'], [Mon..Fri, Sun], [] for the empty set.

Operator Meaning Example
in Membership test Wed in weekdays
+ Union [1,2] + [2,3] is [1,2,3]
- Difference [1,2,3] - [2] is [1,3]
* Intersection [1,2,3] * [2,3,4] is [2,3]
=, <> Equality
<=, >= Subset, superset [1] <= [1,2] is True

Include(s, x) and Exclude(s, x) add and remove one element in place, and are faster than s := s + [x].

Sets can have at most 256 elements in standard Pascal (the base type must have no more than 256 values), so set of Integer is illegal, but set of Byte and set of Char are fine. Free Pascal and Delphi store a small set as a bit array: one bit per possible element, which makes set operations as fast as bitwise operators.

A classic use is replacing long chains of or:

PASCAL
if c in ['a', 'e', 'i', 'o', 'u'] then
  WriteLn('vowel');

instead of (c = 'a') or (c = 'e') or ....

Flags with sets

Delphi's own libraries use sets for options everywhere. Mouse shift states, file attributes and font styles are all sets of small enumerations. A code editor might define:

PASCAL
type
  TStyle = (stBold, stItalic, stUnderline);
  TStyles = set of TStyle;

var
  style: TStyles;
begin
  style := [stBold];
  Include(style, stItalic);
  Exclude(style, stBold);
  if stItalic in style then
    WriteLn('italic');
end.

This reads far better than testing bits by hand.

Stand-ins in C

C has enum but no set type; programmers represent a set with the bits of an integer, which is exactly how Pascal stores one. These programs are C.

C C stand-in: a set of days as bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: Succ, Pred and Ord

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given TDay = (Mon, Tue, Wed, ...), what is Ord(Wed)?

    Enumeration values are numbered from 0, so Mon is 0, Tue is 1 and Wed is 2.
  2. 2. Which declaration defines a type holding the integers 0 to 100 only?

    A subrange is written low..high. With {$R+} assigning a value outside it is an error.
  3. 3. What does [1, 2, 3] * [2, 3, 4] produce?

    * on sets is intersection: the elements present in both sets.
  4. 4. Which is not allowed as a set base type in standard Pascal?

    A set can have at most 256 possible elements, so set of Integer is illegal. Byte, Char and enumerations are fine.
  5. 5. What is Include(s, x) for?

    Include adds an element to a set variable in place; Exclude removes one. in tests membership.

Summary

  • Enumerations name a list of values; they are ordinal, numbered from 0, and type-checked.
  • Subranges restrict an ordinal type, e.g. 0..100, and give free bug detection with {$R+}.
  • Sets (set of T) hold distinct values of an ordinal base type with at most 256 values; use in, +, -, *, Include and Exclude.
  • Sets are stored as bit arrays, which is why they are fast.

Next: If, Else and Case