Describing data
Wirth titled one of his books Algorithms + Data Structures = Programs, and Pascal gives data structures equal billing. Its arrays may be indexed by any ordinal type, so rainfall can be indexed by month rather than by a number you must remember to translate. Its records group named fields of different types, and a variant part can change which fields exist. And it has a feature almost no other mainstream language has built in: sets, with union, intersection and membership as operators, ideal for flags, options and categories.
Object Pascal added what modern programs need: dynamic arrays that grow at run time, records with methods, and long strings that manage their own memory. Each comes with a rule worth learning carefully, because two of these types look alike but behave differently on assignment: strings are copied, dynamic arrays are shared.
Structured types at a glance
| Type | Example declaration | Assignment B := A | Notes |
|---|---|---|---|
| static array | array[TMonth] of Integer | copies every element | size fixed at compile time; any ordinal index range |
| dynamic array | array of Integer | shares: both names refer to one array | indices start at 0; SetLength, Length, High, Copy |
| open array parameter | const A: array of Integer | (parameters only) | accepts any array of that element type, indices 0 .. High(A) |
| record | record Name: string; Age: Integer; end | copies every field | may have a variant part and, with a mode switch, methods |
| set | set of TAllergen | copies | at most 256 elements of an ordinal type |
string (AnsiString) | string with {$H+} | behaves as a copy (copy-on-write) | indices start at 1; reference-counted and freed automatically |
Definition— Open array parameter
A parameter declared array of T (with no index range) accepts a static array, a dynamic array, or a literal list in brackets such as [1, 2, 3]. Inside the routine it is indexed from 0 to High(A), whatever the caller's bounds.
Definition— Variant record
A record whose last part is a case on a tag field. The fields of the different variants share the same memory, so only the variant selected by the tag should be used. Unlike Ada, Pascal does not check this: reading the wrong variant gives you whatever bytes are there.
Dynamic arrays, strings and interfaces are managed types: the compiler inserts code that counts references and frees the memory when the last reference disappears. You never free them yourself. Static arrays, records and sets of simple types live wherever they are declared, on the stack or inside another structure.
Arrays and records
Static, open and dynamic arrays
program Arrays;
{$mode objfpc}{$H+}
type
TMonth = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);
TRainfall = array[TMonth] of Integer; { a static array, indexed by month }
TIntArray = array of Integer; { a dynamic array }
{ An open array parameter accepts any array of Integer, static or dynamic. }
function Sum(const Values: array of Integer): Integer;
var
V: Integer;
begin
Result := 0;
for V in Values do
Result := Result + V;
end;
const
{ Monthly rainfall in mm for a city with a long rainy season (illustrative). }
Rain: TRainfall = (180, 120, 140, 230, 300, 80, 20, 30, 40, 160, 290, 260);
var
M, Wettest: TMonth;
Readings, Copied, Shared: TIntArray;
I: Integer;
begin
Wettest := Jan;
for M := Low(TMonth) to High(TMonth) do
if Rain[M] > Rain[Wettest] then
Wettest := M;
WriteLn('Wettest month: ', Wettest, ' with ', Rain[Wettest], ' mm');
WriteLn('Yearly total: ', Sum(Rain), ' mm');
WriteLn('Sum of a literal open array: ', Sum([1, 2, 3, 4]));
SetLength(Readings, 5); { indices 0 .. 4 }
for I := 0 to High(Readings) do
Readings[I] := (I + 1) * 10;
WriteLn('Length ', Length(Readings), ', Low ', Low(Readings), ', High ', High(Readings));
Shared := Readings; { both names refer to ONE array }
Copied := Copy(Readings); { a separate copy }
Readings[0] := 999;
WriteLn('Readings[0] = ', Readings[0], ', Shared[0] = ', Shared[0], ', Copied[0] = ', Copied[0]);
SetLength(Readings, Length(Readings) + 1); { grow by one }
Readings[High(Readings)] := 60;
WriteLn('After growing: length ', Length(Readings), ', sum ', Sum(Readings));
end.It prints:
Wettest month: May with 300 mm
Yearly total: 1850 mm
Sum of a literal open array: 10
Length 5, Low 0, High 4
Readings[0] = 999, Shared[0] = 999, Copied[0] = 10
After growing: length 6, sum 1199TRainfall is indexed by TMonth, so Rain[May] needs no translation and a loop over Low(TMonth) .. High(TMonth) cannot miss a month. The typed constant Rain is initialised with a list in parentheses. Sum takes an open array, so it accepts the static Rain, the literal [1, 2, 3, 4] and, later, the dynamic Readings.
The fifth line is the one to remember. Shared := Readings did not copy the array: both variables refer to the same block of memory, so changing Readings[0] changed Shared[0] too. Copy(Readings) made an independent copy. Code that passes dynamic arrays around and modifies them must decide deliberately which it wants. SetLength grows an array (keeping its contents); calling it inside a loop to add one element at a time is slow for large arrays, so collect into a list class (Lesson 7) or grow in larger steps.
Records: variants, with and methods
program Records;
{$mode objfpc}{$H+}
{$modeswitch advancedrecords} { lets records have methods }
uses
SysUtils;
type
TShapeKind = (skCircle, skRectangle);
{ A variant record: which fields exist depends on Kind. }
TShape = record
Name: string;
case Kind: TShapeKind of
skCircle: (Radius: Double);
skRectangle: (Width, Height: Double);
end;
{ An advanced record: data plus methods, still a value type. }
TMoney = record
Cents: Int64;
function ToString: string;
class function Make(AUnits, ACents: Int64): TMoney; static;
end;
function TMoney.ToString: string;
begin
Result := IntToStr(Cents div 100) + '.' + Copy(IntToStr(100 + Cents mod 100), 2, 2);
end;
class function TMoney.Make(AUnits, ACents: Int64): TMoney;
begin
Result.Cents := AUnits * 100 + ACents;
end;
function Area(const S: TShape): Double;
begin
case S.Kind of
skCircle: Result := Pi * Sqr(S.Radius);
skRectangle: Result := S.Width * S.Height;
end;
end;
var
Shapes: array[1..2] of TShape;
S: TShape;
Price, Copy2: TMoney;
begin
Shapes[1].Name := 'pond';
Shapes[1].Kind := skCircle;
Shapes[1].Radius := 3;
with Shapes[2] do { "with" opens a record's fields as names }
begin
Name := 'garden';
Kind := skRectangle;
Width := 12;
Height := 7.5;
end;
for S in Shapes do
WriteLn(S.Name:8, ' ', S.Kind, ' area ', Area(S):0:2);
Price := TMoney.Make(19, 5);
Copy2 := Price; { records are copied on assignment }
Copy2.Cents := Copy2.Cents * 3;
WriteLn('Price ', Price.ToString, ', three of them ', Copy2.ToString);
end.It prints:
pond skCircle area 28.27
garden skRectangle area 90.00
Price 19.05, three of them 57.15TShape is a variant record: a circle has a Radius, a rectangle a Width and Height, and Kind says which. Area uses a case on the tag, the only safe way to read a variant. The with statement lets the block refer to Shapes[2]'s fields by their bare names; it is convenient but can be confusing when two records in scope have fields of the same name, and many style guides limit it to short blocks.
TMoney is an advanced record (enabled by {$modeswitch advancedrecords}, and always available in delphi mode): a record with methods, here a ToString function and a static "constructor" Make. It is still a value type, so Copy2 := Price copied it, and tripling Copy2 left Price alone. Advanced records are the idiomatic choice for small value types such as money, points, dates and complex numbers. Notice the parameters AUnits and ACents: a first draft named them Units and Cents, and the compiler stopped with Error: Duplicate identifier "Cents", because inside a record's methods the field names are already in scope. The A prefix convention exists to avoid exactly this.
Sets and strings
Sets
A Pascal set holds any combination of up to 256 values of an ordinal type, stored as bits, and its operators are the operators of set theory: + union, * intersection, - difference, in membership, <= and >= subset and superset, and = equality. Include and Exclude add and remove single elements.
program Sets;
{$mode objfpc}{$H+}
type
TAllergen = (Gluten, Milk, Egg, Peanut, Soy, Sesame, Fish);
TAllergens = set of TAllergen;
TDish = record
Name: string;
Contains: TAllergens;
end;
const
Menu: array[1..4] of TDish = (
(Name: 'injera with lentils'; Contains: [Gluten]),
(Name: 'pad thai'; Contains: [Egg, Peanut, Soy, Fish]),
(Name: 'hummus'; Contains: [Sesame]),
(Name: 'rice and beans'; Contains: [])
);
procedure Show(const Title: string; A: TAllergens);
var
X: TAllergen;
begin
Write(Title, ': [');
for X in A do
Write(' ', X);
WriteLn(' ]');
end;
var
Guest, Everything: TAllergens;
D: TDish;
Vowels: set of Char;
begin
Guest := [Peanut, Sesame];
Include(Guest, Milk); { add one element }
Show('Guest avoids', Guest);
Everything := [];
for D in Menu do
begin
Everything := Everything + D.Contains; { union }
if D.Contains * Guest = [] then { intersection is empty }
WriteLn(' safe: ', D.Name)
else
Show(' avoid ' + D.Name + ', because of', D.Contains * Guest);
end;
Show('Allergens anywhere on the menu', Everything);
Show('Never on the menu', [Low(TAllergen)..High(TAllergen)] - Everything);
WriteLn('Is [Egg, Soy] a subset of the menu''s allergens? ', [Egg, Soy] <= Everything);
Vowels := ['a', 'e', 'i', 'o', 'u'];
WriteLn('''y'' in Vowels? ', 'y' in Vowels);
end.It prints:
Guest avoids: [ Milk Peanut Sesame ]
safe: injera with lentils
avoid pad thai, because of: [ Peanut ]
avoid hummus, because of: [ Sesame ]
safe: rice and beans
Allergens anywhere on the menu: [ Gluten Egg Peanut Soy Sesame Fish ]
Never on the menu: [ Milk ]
Is [Egg, Soy] a subset of the menu's allergens? TRUE
'y' in Vowels? FALSED.Contains * Guest = [] asks "do these sets have nothing in common?" in one expression, and [Low(TAllergen)..High(TAllergen)] - Everything lists the allergens that appear nowhere. A for … in loop visits a set's elements in order. Delphi and Lazarus use sets everywhere for options: a font style is a set such as [fsBold, fsItalic], and StringReplace, which you will see next, takes a set of flags such as [rfReplaceAll].
Strings
With {$H+}, string means AnsiString: a reference-counted, heap-allocated sequence of bytes that can be as long as memory allows. Assignment is cheap (it shares the bytes), and the first write to a shared string makes a private copy (copy-on-write), so strings behave like values even though dynamic arrays do not. Indexing starts at 1: S[1] is the first character and S[Length(S)] the last.
program Strings;
{$mode objfpc}{$H+}
uses
SysUtils, StrUtils;
var
Line, City, Copy1: string;
Comma, Number: Integer;
Parts: TStringArray;
P: string;
begin
Line := ' Ama Mensah, Kumasi ';
Line := Trim(Line);
Comma := Pos(',', Line); { 1-based; 0 if absent }
WriteLn('[', Line, '] length ', Length(Line), ', comma at ', Comma);
WriteLn('Name: ', Copy(Line, 1, Comma - 1));
City := Copy(Line, Comma + 2, MaxInt); { to the end }
WriteLn('City: ', City, ', first letter ', City[1]);
Copy1 := City; { strings behave like values }
Copy1[1] := 'k';
WriteLn('City = ', City, ', Copy1 = ', Copy1);
WriteLn(UpperCase(Line));
WriteLn(StringReplace('a-b-c', '-', ' + ', [rfReplaceAll]));
WriteLn(ReverseString('stressed'));
Parts := 'red,green,,blue'.Split([',']);
Write(Length(Parts), ' parts:');
for P in Parts do
Write(' [', P, ']');
WriteLn;
if TryStrToInt('2026', Number) then
WriteLn('Parsed ', Number + 1);
if not TryStrToInt('twenty', Number) then
WriteLn('''twenty'' is not a number');
WriteLn('Length of ''São Paulo'' in bytes: ', Length('São Paulo'));
WriteLn(Format('%-10s|%6.2f|%4d', ['left', 3.14159, 42]));
end.It prints:
[Ama Mensah, Kumasi] length 18, comma at 11
Name: Ama Mensah
City: Kumasi, first letter K
City = Kumasi, Copy1 = kumasi
AMA MENSAH, KUMASI
a + b + c
desserts
4 parts: [red] [green] [] [blue]
Parsed 2027
'twenty' is not a number
Length of 'São Paulo' in bytes: 10
left | 3.14| 42The routines shown are the ones you will use most. Trim removes surrounding spaces, Pos finds a substring (returning 0 if absent), and Copy(S, Start, Count) extracts part of a string; a count of MaxInt means "to the end". Changing Copy1[1] did not affect City, thanks to copy-on-write. StringReplace with the flag set [rfReplaceAll] replaces every occurrence, and ReverseString comes from StrUtils. '…'.Split([',']) is a type helper method from SysUtils, returning a TStringArray that keeps empty fields. TryStrToInt parses without raising an exception; StrToInt would raise EConvertError on bad input.
The last lines show that Free Pascal strings are bytes. The source file is UTF-8, so 'São Paulo' holds 10 bytes for 9 characters, since ã takes two. Lazarus's LCL treats string as UTF-8 throughout, and its LazUTF8 unit offers character-aware routines such as UTF8Length. Delphi, by contrast, has used UTF-16 UnicodeString as string since 2009, so Length counts UTF-16 code units there. Code that indexes strings character by character needs care in both.
Common misunderstandings
Misconception
"Assigning a dynamic array copies it." It copies a reference. Both variables then share one array until SetLength or Copy gives one of them its own. Strings, which look similar, are copied on write; dynamic arrays are not.
Misconception
"Strings start at 0, like arrays." Pascal strings start at 1 (the old ShortString kept its length in element 0). Dynamic arrays and open array parameters start at 0. Use Low and High where you can, and remember which is which where you cannot.
Misconception
"A variant record is checked like Ada's." Pascal lets you read any variant's fields whatever the tag says, and you get the bytes of whatever was stored last. Always test the tag with case before reading variant fields.
Misconception
"Length counts characters." It counts bytes for Free Pascal's UTF-8 strings and UTF-16 code units for Delphi's strings. For user-visible character counts, use Unicode-aware routines.
Exercises
All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.
1. Arrays, records, sets and strings
CoreComputationalA, B and C are dynamic arrays of Integer. What does this print?
A := [1, 2, 3];
B := A;
C := Copy(A);
B[1] := 50;
WriteLn(A[1], ' ', C[1]);
2. Arrays, records, sets and strings
Warm-upComputationalAfter SetLength(A, 7); for a dynamic array A, what is High(A)?
3. Arrays, records, sets and strings
CoreComputationalWhat does WriteLn(Copy('Kumasi', 2, 3), ' ', Pos('a', 'Kumasi')); print?
4. Arrays, records, sets and strings
Warm-upComputationalWhich elements are in [Gluten, Milk, Egg] * [Milk, Egg, Soy]?
5. Arrays, records, sets and strings
CoreComputationalIn the allergen program, the guest's set becomes [Gluten, Sesame] (and Include(Guest, Milk) is removed). How many dishes are printed as safe?
6. Arrays, records, sets and strings
StretchComputationalIn a UTF-8 source file compiled by Free Pascal 3.2.2 with {$H+}, what does Length('Zürich') return?
7. Arrays, records, sets and strings
CoreComputationalHow many elements does 'a,,b'.Split([',']) return?
8. Arrays, records, sets and strings
CoreHumanS and T are strings and A and B dynamic arrays. After T := S; T[1] := 'x'; and B := A; B[0] := 9;, which original variables have changed?
Further reading and resources
- Free Pascal Reference Guide: Structured typesArrays, records, sets, strings and their exact rules.
- Free Pascal RTL reference: SysUtils and StrUtilsFormat, Trim, StringReplace, TryStrToInt and hundreds of other string routines.
- Free Pascal wikiCommunity articles on dynamic arrays, strings and Unicode in Free Pascal and Lazarus.