8.2.8 Set types

A set is stored as an array of bits, where each bit indicates if the element is in the set or excluded from the set. The maximum number of elements in a set is 256.

How many bytes the compiler uses to store a sets depends on the mode. For non-Delphi modes, the compiler stores small sets (less than 32 elements) in a Longint, if the set element type range allows it. This allows for faster processing and decreases program size. Otherwise, sets are stored in 32 bytes.

For Delphi mode, the compiler tries to store the set in the smallest number of bytes in which the set will fit.

The following program illustrates this:

Type
  TSet1 = Set of 0..1;
  TSet2 = Set of 0..8;
  TSet3 = Set of 0..16;
  TSet4 = Set of 0..128;
  TSet5 = Set of 0..247;
  TSet6 = Set of 0..255;

begin
  Writeln('Set 1: ',SizeOf(TSet1));
  Writeln('Set 2: ',SizeOf(TSet2));
  Writeln('Set 3: ',SizeOf(TSet3));
  Writeln('Set 4: ',SizeOf(TSet4));
  Writeln('Set 5: ',SizeOf(TSet5));
  Writeln('Set 6: ',SizeOf(TSet6));
end.

When compiled in fpc mode, the program outputs the following:

Set 1: 4
Set 2: 4
Set 3: 4
Set 4: 32
Set 5: 32
Set 6: 32

In Delphi mode, the program will print:

Set 1: 1
Set 2: 2
Set 3: 4
Set 4: 17
Set 5: 31
Set 6: 32

Note that the set element size can be influenced with the {$PACKSET } directive, section 1.2.63, page 170.

The longword number of a specific element E is given by :

 LongwordNumber = (E div 32);

and the bit number within that 32-bit value is given by:

 BitNumber = (E mod 32);