Reading — step 1 of 5
Learn
~2 min readStrings, Arrays, Types
Pascal has rich type definitions. Group them in a type block before var.
Enumerations
type
TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
TColor = (Red, Green, Blue);
var
today: TDay;
begin
today := Wed;
WriteLn(Ord(today)); { 2 — index in declaration order }
end.
Enumerations are ordinal — you can use them in case, for ... to, and set of:
for d := Mon to Fri do ...
case today of
Mon..Fri: WriteLn('weekday');
Sat, Sun: WriteLn('weekend');
end;
weekdays: set of TDay = [Mon..Fri];
Successor / predecessor:
Succ(Mon) { Tue }
Pred(Wed) { Tue }
Subranges
A subrange of an ordinal type — runtime-checked when range checking is on:
type
TPercent = 0..100;
TLetter = 'a'..'z';
var grade: TPercent;
begin
grade := 95; { OK }
{ grade := 200; } { compile error or runtime error }
end.
Type aliases
Give a friendly name to existing types:
type
TUserID = integer;
TName = string;
TIntArray = array of integer;
var id: TUserID;
The compiler treats TUserID and integer as compatible. For stricter types (incompatible aliases), use type integer:
type
TMeters = type integer; { distinct — won't auto-convert from integer }
Constants
const
MAX_USERS = 1000;
PI = 3.14159;
GREETING = 'Hello, World!';
Typed constants — initialized variables that act like constants:
const
days: array[1..7] of string = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
config: record
host: string;
port: integer;
end = (host: 'localhost'; port: 8080);
Typedefs in practice
Real Pascal code uses types extensively to:
- Document intent (
TPercentnotinteger) - Catch mistakes (subranges, distinct types)
- Enable polymorphism (class hierarchies)
- Enable generics (
TList<TUser>)
This is what made Pascal a great teaching language — types make programs self-documenting and compiler-checked.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…