Types that say what values mean
Wirth's great contribution to everyday programming was the idea that a programmer should describe the data as carefully as the algorithm. In Pascal you do not just store "a number": you declare that a value is a day of the week, an hour from 0 to 23, or a percentage from 0 to 100, and the compiler holds you to it. Many of the conventions you take for granted in later languages, such as enumerations with names rather than magic numbers, come from this habit.
Pascal also gives you a small, regular set of control statements, each with one clear purpose: if for a choice, case for a choice among many values, for for counting, while for a loop that may not run at all, and repeat for one that runs at least once. Learn them well and most programs write themselves.
This lesson has one warning in it that every Free Pascal programmer learns, sooner or later, the hard way: by default the compiler does not check that values stay inside their declared ranges. You will see what happens then and how to switch the checks on.
Pascal's simple types
Definition— Ordinal type
A type whose values can be counted in order: every integer type, Char, Boolean, enumerations and subranges. Each value has a position, Ord(X), a successor and a predecessor, and ordinal types may be used as case selectors, array indices, for loop counters and set elements.
| Type | Size | Range or precision |
|---|---|---|
Byte, ShortInt | 1 byte | 0 .. 255, -128 .. 127 |
Word, SmallInt | 2 bytes | 0 .. 65535, -32768 .. 32767 |
Cardinal, LongInt | 4 bytes | 0 .. 4294967295, about ±2.1 × 10⁹ |
Int64, QWord | 8 bytes | about ±9.2 × 10¹⁸, 0 .. about 1.8 × 10¹⁹ |
Integer | 2 or 4 bytes | SmallInt in the default mode, LongInt in objfpc and delphi |
Single, Double | 4, 8 bytes | about 7 and 15–16 significant digits |
Extended | 10 bytes on x86 | about 19 digits (on many other processors the same as Double) |
Currency | 8 bytes | fixed point, exactly 4 decimal places |
Char, Boolean | 1 byte | a byte-sized character; False, True |
You can declare your own ordinal types:
type
TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); { an enumeration }
TWeekday = Mon..Fri; { a subrange of TDay }
TPercent = 0..100; { a subrange of Integer }An enumeration lists its values by name; Ord(Mon) is 0. A subrange is a part of another ordinal type, compatible with it in expressions. The ordinal routines work on all of them: Ord, Succ, Pred, Low and High (the first and last values of a type), Inc(X) and Dec(X) (add or subtract one, in place), and Chr (from a number to a Char).
Unlike Ada, Pascal subranges do not create incompatible types: a TPercent and an Integer mix freely, and the subrange only restricts what may be stored. Whether that restriction is checked is up to a compiler switch, which is the subject of the second example below.
Enumerations, subranges and range checking
A week of opening hours
program Days;
{$mode objfpc}{$H+}
type
TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); { an enumeration }
TWeekday = Mon..Fri; { a subrange of it }
THour = 0..23; { a subrange of Integer }
var
D: TDay;
Opening: THour;
Hours: Integer;
begin
Hours := 0;
for D := Low(TDay) to High(TDay) do
begin
case D of
Mon..Thu: Opening := 8;
Fri: Opening := 9;
else
Continue; { closed: skip the rest of this pass }
end;
Hours := Hours + (17 - Opening);
WriteLn(D, ' opens at ', Opening, ':00');
end;
WriteLn('Open hours per week: ', Hours);
D := Wed;
WriteLn('Ord(Wed) = ', Ord(D), ', Succ(Wed) = ', Succ(D), ', Pred(Wed) = ', Pred(D));
WriteLn('Weekdays: ', Low(TWeekday), ' to ', High(TWeekday));
WriteLn('Is Sat a weekday? ', (Sat >= Low(TWeekday)) and (Sat <= High(TWeekday)));
WriteLn('Character 65 is ', Chr(65), ', and Ord(''a'') is ', Ord('a'));
end.It prints:
Mon opens at 8:00
Tue opens at 8:00
Wed opens at 8:00
Thu opens at 8:00
Fri opens at 9:00
Open hours per week: 44
Ord(Wed) = 2, Succ(Wed) = Thu, Pred(Wed) = Tue
Weekdays: Mon to Fri
Is Sat a weekday? FALSE
Character 65 is A, and Ord('a') is 97Free Pascal can WriteLn an enumeration value by name, which is convenient for debugging (Delphi cannot; it needs the TypInfo unit's GetEnumName). The case statement chooses on an ordinal value: a branch may name a single value, a list (Sat, Sun) or a range (Mon..Thu), and the optional else part covers everything else. Here else runs Continue, which skips to the next pass of the loop, so closed days print nothing. Booleans print in capitals as TRUE and FALSE.
Range checking
What happens if a battery level of type TPercent goes above 100?
program Ranges;
{$mode objfpc}{$H+}
uses
SysUtils; { turns run-time errors into exceptions }
type
TPercent = 0..100;
var
Battery: TPercent;
Small: Byte;
Step: Integer;
begin
{ Checks off (the compiler's default): out-of-range values slip through. }
{$R-}{$Q-}
Step := 30;
Battery := 90;
Battery := Battery + Step;
WriteLn('Unchecked: battery at ', Battery, '%');
Small := 250;
Small := Small + 10;
WriteLn('Unchecked: 250 + 10 as a Byte = ', Small);
{ Checks on: the same mistakes raise exceptions. }
{$R+}{$Q+}
try
Battery := 90;
Battery := Battery + Step;
WriteLn('not reached');
except
on E: ERangeError do
WriteLn('Checked: ', E.ClassName, ': ', E.Message);
end;
try
Small := 250;
Small := Small + 10;
WriteLn('not reached');
except
on E: Exception do
WriteLn('Checked: ', E.ClassName, ': ', E.Message);
end;
end.It prints:
Unchecked: battery at 120%
Unchecked: 250 + 10 as a Byte = 4
Checked: ERangeError: Range check error
Checked: ERangeError: Range check errorWith checks off, which is Free Pascal's default, the battery happily reports 120%, a value its type says is impossible, and a Byte silently wraps around from 260 to 4. With {$R+} (range checks) and {$Q+} (overflow checks) switched on, the same assignments raise ERangeError, which try … except catches. (Exceptions are covered properly in Lesson 7. Using the SysUtils unit is what turns these run-time errors into exceptions; without it, the program would stop with "Runtime error 201".) In the Byte case the addition itself is done in a wider integer type, so it is the range check on assignment that fires.
Professional Pascal programmers switch both checks on for debug builds, either with directives at the top of each file or with the -Cr -Co compiler options (Lazarus has check boxes for them), and many keep them on in release builds too. The cost is small; the bugs they catch are not.
Control flow
The statements, in brief:
if Temperature > 30 then
OpenWindows
else if Temperature < 10 then
StartHeater
else
WriteLn('Comfortable');Each branch is one statement; use begin … end for several. Conditions must be Boolean. By default and and or short-circuit: in if (Count > 0) and (Total div Count > 10), the division is skipped when Count is 0.
Pascal has three loops, and all of them appear in this program:
program Loops;
{$mode objfpc}{$H+}
var
Savings: Double;
Year, N, Steps, Vowels, Countdown: Integer;
C: Char;
begin
{ while: test first, may run zero times }
N := 27;
Steps := 0;
while N <> 1 do
begin
if N mod 2 = 0 then
N := N div 2
else
N := 3 * N + 1;
Inc(Steps);
end;
WriteLn('27 reaches 1 in ', Steps, ' steps');
{ repeat ... until: test last, always runs at least once }
Savings := 1000.0;
Year := 0;
repeat
Savings := Savings * 1.07;
Inc(Year);
until Savings >= 2000.0;
WriteLn('At 7% a year, money doubles after ', Year, ' years: ', Savings:0:2);
{ for ... downto, with Break }
for Countdown := 10 downto 1 do
begin
if Countdown mod 7 = 0 then
begin
WriteLn('Stopped at ', Countdown);
Break;
end;
Write(Countdown, ' ');
end;
{ for ... in walks over the characters of a string }
Vowels := 0;
for C in 'Ouagadougou' do
if LowerCase(C) in ['a', 'e', 'i', 'o', 'u'] then
Inc(Vowels);
WriteLn('Vowels in Ouagadougou: ', Vowels);
end.It prints:
27 reaches 1 in 111 steps
At 7% a year, money doubles after 11 years: 2104.85
10 9 8 Stopped at 7
Vowels in Ouagadougou: 8while Condition dotests before each pass and may run zero times.repeat … until Conditiontests after each pass, so it always runs at least once, and it loops until the condition becomes true (the opposite sense fromwhile). It needs nobegin … end, sincerepeatanduntilalready bracket the statements.for Var := First to Last docounts up by one, anddowntocounts down. The counter must be an ordinal local variable, you must not assign to it inside the loop, and its value after the loop is undefined, so do not use it. The bounds are evaluated once, before the loop starts.for C in Something dovisits each element of a string, array or set.Breakleaves the innermost loop,Continuestarts its next pass, andExitleaves the current procedure (or the program, from the main block).C in ['a', 'e', 'i', 'o', 'u']tests membership in a set, a Pascal speciality that Lesson 4 covers.
Numbers that surprise
program Numbers;
{$mode objfpc}{$H+}
var
A, B: Double;
Price, Total: Currency;
I: Integer;
begin
WriteLn('Byte: ', Low(Byte), ' .. ', High(Byte));
WriteLn('Integer: ', Low(Integer), ' .. ', High(Integer));
WriteLn('Int64: ', High(Int64));
A := 0.1;
B := 0.2;
WriteLn('0.1 + 0.2 = 0.3 as Double? ', A + B = 0.3);
WriteLn('0.1 + 0.2 to 17 decimals: ', A + B:0:17);
Price := 0.10;
Total := 0;
for I := 1 to 3 do
Total := Total + Price;
WriteLn('3 x 0.10 = 0.30 as Currency? ', Total = 0.30);
WriteLn('Trunc(2.7) = ', Trunc(2.7), ', Round(2.7) = ', Round(2.7));
WriteLn('Round(2.5) = ', Round(2.5), ', Round(3.5) = ', Round(3.5));
WriteLn('7 / 2 = ', 7 / 2:0:1, ', 7 div 2 = ', 7 div 2, ', -7 div 2 = ', -7 div 2,
', -7 mod 2 = ', -7 mod 2);
end.It prints:
Byte: 0 .. 255
Integer: -2147483648 .. 2147483647
Int64: 9223372036854775807
0.1 + 0.2 = 0.3 as Double? FALSE
0.1 + 0.2 to 17 decimals: 0.30000000000000004
3 x 0.10 = 0.30 as Currency? TRUE
Trunc(2.7) = 2, Round(2.7) = 3
Round(2.5) = 2, Round(3.5) = 4
7 / 2 = 3.5, 7 div 2 = 3, -7 div 2 = -3, -7 mod 2 = -1Three lessons hide in these lines. Binary floating point cannot represent 0.1 exactly, so 0.1 + 0.2 is not quite 0.3; compare real numbers with a tolerance, never with =. Currency is a fixed-point type that stores amounts as whole ten-thousandths, so sums of prices are exact; use it, or integers of cents, for money. And Round uses banker's rounding: a value exactly halfway is rounded to the even neighbour, so 2.5 becomes 2 and 3.5 becomes 4. This reduces bias in long sums, and surprises everyone once. div truncates toward zero, and mod takes the sign of the left operand.
Common misunderstandings
Misconception
"if X > 0 and Y > 0 then tests both conditions." In Pascal, and binds more tightly than >, so this means X > (0 and Y) > 0, a bitwise and of 0 and Y followed by a nonsensical comparison. Free Pascal 3.2.2 rejects it with Error: Incompatible types: got "Boolean" expected "Int64". Always parenthesise comparisons: if (X > 0) and (Y > 0) then.
Misconception
"A semicolon before else is harmless." It ends the if statement, leaving else with nothing to belong to. The compiler stops with Fatal: Syntax error, ";" expected but "ELSE" found. Inside a case statement, however, a semicolon before else is allowed, because there else belongs to the case.
Misconception
"Declaring a subrange makes the compiler check it." Assigning an out-of-range constant, such as Battery := 150, only draws a warning (range check error while evaluating constants (150 must be between 0 and 100)), and computed values are checked at run time only with {$R+}, which is off by default in Free Pascal. Switch it on.
Misconception
"Round rounds halves up." Free Pascal's and Delphi's Round round halves to the nearest even number (banker's rounding). When you need halves rounded away from zero, the Math unit's SimpleRoundTo(X, 0) does it: it gave 3 for 2.5 and -3 for -2.5.
Exercises
All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.
1. Types and control flow
Warm-upComputationalWith type TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);, what does WriteLn(Ord(Sun), ' ', Pred(Sun), ' ', Succ(Mon)); print in Free Pascal?
2. Types and control flow
CoreComputationalWhat does WriteLn(Round(4.5), ' ', Round(5.5), ' ', Round(-2.5), ' ', Trunc(-2.7)); print?
3. Types and control flow
CoreComputationalIn the loops program, the growth rate is changed from 1.07 to 1.10. After how many years does the repeat loop stop?
4. Types and control flow
CoreComputationalN starts at 0 each time. After which loops is N equal to 1? Give the letters.
- a:
repeat Inc(N); until True; - b:
while False do Inc(N); - c:
for I := 1 to 1 do Inc(N); - d:
for I := 1 downto 2 do Inc(N);
5. Types and control flow
CoreComputationalWhat does this print?
for I := 10 downto 1 do
begin
if I mod 4 = 0 then
begin
Write('stop');
Break;
end;
Write(I, ' ');
end;
6. Types and control flow
Warm-upComputationalThe vowel-counting loop is run on 'Antananarivo', the capital of Madagascar. How many vowels does it count?
7. Types and control flow
CoreComputationalWhich condition correctly tests that both X and Y are positive?
8. Types and control flow
StretchComputationalWhat does WriteLn(-17 div 5, ' ', -17 mod 5); print in Free Pascal?
Further reading and resources
- Free Pascal Reference Guide: TypesEvery ordinal, real and string type with its range and size.
- Free Pascal Programmer's Guide: compiler directives{R+}, {Q+}, {$B-} and the other switches that change how code is checked and compiled.
- Free Pascal wikiCommunity articles on data types, loops and common pitfalls.