Programming in Pascal

Reading map

Previous: Foundations Reading map Next: Assembly Language

Volume I: Foundations of Programming (Chapter 2)Code & tests Chapter diagrams Download editable SVGs

Pascal is used here as a teaching language, not as the final goal. The useful thing to learn is imperative programming: variables, statements, control flow, procedures, recursion, data structures, files, testing, and modularity.

The dialect assumed in these notes is Free Pascal. Pascal has many dialects, so portable code should avoid relying on accidental features unless they are clearly Free Pascal features.

Chapter Map

Detailed notes - 2: Pascal and the beginnings of programming

1

Pascal:

  • introduced by Niklaus Wirth in 1970 for teaching programming
  • used here to move from discussing computers to writing programs

2

Pascal dialects:

  • different implementations added extensions and changed the language
  • the name alone does not identify one precise set of rules
  • distinguish the original language, standards, and implementation dialects

3

Free Pascal:

  • compiler begun by Florian Paul Klaempfl in 1993
  • supports several Pascal dialects and operating systems
  • supplies many facilities beyond those used in this book

4

limited teaching subset:

  • learn imperative programming through Pascal examples
  • practise structured programming, recursion, pointers, and other basics
  • prepare for C and C++; learning every Free Pascal extension is unnecessary

5

further study and choice of professional tools:

  • readers can study other Pascal facilities independently
  • the author's preference for other languages is a later practical question

6

main subject = programming

  • Pascal supplies the examples and a way to experiment

First Programs

A Pascal program is ordinary text, usually saved with the .pas suffix and compiled with fpc:

fpc hello.pas
./hello

A minimal program has a heading, a main block, and a final dot:

program hello;
begin
    writeln('Hello, world!');
end.

Important syntax:

Fragment Meaning
program hello; Program heading and program name
begin ... end Operator brackets: a block of statements
writeln(...) Output followed by a newline
'text' String literal
. after final end End of the whole program

write prints without a newline; writeln prints and then ends the line. read and readln read values from standard input.

Compiler messages matter:

Kind Meaning
Fatal / Error Compilation failed
Warning Legal code, but probably suspicious
Note Legal code, but the compiler noticed something unusual

Read the first error first. Later errors are often consequences of the first one.

Detailed notes - 2.1: First programs

1

CPU executes machine code

  • writing it directly is laborious
  • source code: text following a programming language's rules
  • compiler: translates the program into another representation
  • interpreter: carries out the actions described by the program

2

Pascal workflow used here:

  • write plain source text in a text editor
  • save with a .pas suffix
  • compile with fpc
  • run the resulting executable

3

experiment directory:

  • mkdir firstprog; cd firstprog
  • ls checks its contents
  • shell prompt identifies user, host, and current directory

4

start an editor with the intended filename:

  • vim hello.pas, joe hello.pas, or nano hello.pas
  • a new file appears when its contents are first saved

5

first program: print Hello, world!

  • program hello; introduces the program and its name
  • identifiers name program entities
  • header ends with a semicolon
  • the book keeps the header even where the compiler permits omission

6

begin:

  • starts the main body
  • later programs also contain declarations and subprograms outside it

7

writeln('Hello, world!'):

  • prints its arguments
  • ln means a newline follows the output

8

terminology of built-in I/O:

  • the author calls writeln a statement because of its special syntax
  • arbitrary argument counts and formatting directives need compiler support
  • its identifier status also explains the common name built-in procedure

9

string literal:

  • characters enclosed in apostrophes represent themselves
  • without quotes, words are interpreted as program identifiers/syntax

10

end.:

  • end closes the main body
  • final dot terminates the program

11

save and inspect the source:

  • ls checks that hello.pas exists
  • cat hello.pas displays this short file
  • Tab completion can supply its filename

12

compile: fpc hello.pas

  • Error / Fatal: compilation cannot produce the requested program
  • warning: valid syntax may still describe suspicious behavior
  • note: a less severe observation
  • the book's particular old linker warning is specific to its environment

13

example errors:

  • writenl: unknown identifier
  • omitted final dot: compiler reaches the end while expecting '.'
  • Fatal stops further processing

14

diagnostic position:

  • filename(row,column) identifies where the problem was detected
  • unexpected end-of-file can be reported after the last written row

15

learn the editor's jump-to-number command:

  • diagnostic positions make locating errors much faster

16

compilation products:

  • hello.pas: source text
  • hello.o: object module used by the linker
  • hello: executable; ls -l shows execute permission
  • runtime support explains why a tiny source can produce a larger executable

17

run the local executable: ./hello

  • '.' means the current directory
  • a command without a slash is searched through PATH
  • current directory need not be in PATH

18

sequential statements:

  • execute in their written order
  • semicolon separates neighboring Pascal statements
  • end is a delimiter; a semicolon before it is unnecessary

19

write versus writeln:

  • two writeln calls produce two output lines
  • write prints without adding a newline
  • after write, the next shell prompt can appear immediately after the text
  • source changes require recompilation before rerunning

20

mixed output example:

  • write('First'); writeln('Second') -> FirstSecond, then newline
  • write('Third'); writeln('Fourth') -> ThirdFourth, then newline
  • output does not insert separators unless requested

21

English terminology:

  • statement: a language construction prescribing an action
  • operator: an operation such as +, *, or a comparison
  • Russian 'оператор' usually means statement in programming

22

mathematical terminology differs:

  • Russian mathematical 'оператор' retains the meaning of English operator

23

keep the programming terms distinct:

  • this becomes especially relevant to the C++ keyword operator

24

source layout in the examples:

  • program header and outer begin/end start at the left margin
  • statements inside the body are indented by four spaces
  • major elements occupy separate lines

25

compiler generally ignores these layout choices:

  • many untidy arrangements compile identically
  • confusing layout makes even one's own unfinished code difficult to follow

26

readability:

  • programmers spend much time reading and modifying existing code
  • source must communicate its structure and behavior to people

27

structural indentation:

  • shift nested constructions right relative to their containing construction
  • expose the nesting at a glance

28

indent width in the book = four spaces

  • different projects use different conventions
  • width should make nesting visible without wasting horizontal space

29

consistency:

  • keep one indentation convention throughout the program
  • apply the same consistency to other formatting decisions

Expressions, Variables, and Statements

Arithmetic and Types

Pascal expressions resemble mathematical formulas:

writeln(2 + 3 * 4);
writeln((2 + 3) * 4);

Common arithmetic operations:

Operation Meaning
+, - Addition, subtraction
* Multiplication
/ Real division
div Integer quotient
mod Integer remainder
unary +, unary - Sign

Examples:

writeln(17 div 5);  { 3 }
writeln(17 mod 5);  { 2 }
writeln(17 / 5);    { real value }

Pascal is strongly typed: each value and variable has a type, and the compiler uses types to reject many meaningless operations before the program runs.

Detailed notes - 2.2.1: Arithmetic operations and the idea of type

1

write / writeln also print computed values:

  • writeln(175*113) prints 19775
  • comma-separated arguments can combine labels and expressions
  • '175*113' prints those characters; 175*113 computes their product

2

arithmetic and precedence:

  • + addition; - subtraction; * multiplication
  • multiplication binds more tightly than addition/subtraction
  • 10 + 5 * 7 = 45; (10 + 5) * 7 = 105

3

unary operators:

  • - changes the sign of one operand
  • + leaves its operand unchanged

4

ordinary division /:

  • produces a floating-point result even for two integer operands
  • writeln(14/7) therefore uses floating-point output formatting

5

numeric types specify distinct representations:

  • integer 2 and floating-point 2.0 need different representations/operations
  • signed integer families: shortint, integer, longint, int64
  • unsigned families: byte, word, longword, qword
  • real: a floating-point type
  • the book uses a mode with 16-bit integer; widths depend on type and mode

6

type describes:

  • possible values
  • representation
  • operations defined for those values

7

non-numeric types:

  • boolean: true / false; logical operations
  • string: text; + concatenates strings
  • comparing strings produces boolean
  • char: one character

8

result type depends on the operation and operands:

  • integer addition/multiplication ordinarily yield integer results
  • floating-point arithmetic yields floating-point results
  • / always gives a floating-point result

9

floating-point output:

  • default display may use mantissa E exponent: m * 10^p
  • explicit formatting: value:field_width:decimal_places
  • writeln(14/7:7:3) prints two spaces followed by 2.000

10

integer division:

  • div: integer quotient
  • mod: remainder
  • 27 div 4 = 6; 27 mod 4 = 3

Variables, Initialization, and Assignment

Variables are declared before the main block:

program sum2;
var
    a, b, s: integer;
begin
    readln(a, b);
    s := a + b;
    writeln(s);
end.

:= means assignment. It changes the value stored in a variable.

Do not confuse:

Symbol Meaning
:= Assignment
= Equality test

A variable should be assigned a meaningful value before it is read. Reading an uninitialized variable is a programming error even if the compiler happens to accept the program.

Detailed notes - 2.2.2: Variables, initialization, and assignment

1

fixed literals limit a program to one particular set of inputs

  • more useful programs solve the same task for different data

2

general solution needs values supplied at run time:

  • read input, store it in memory, then process it
  • Pascal provides variables for this purpose

3

variables across languages:

  • imperative languages use broadly similar mutable storage
  • other paradigms can use variables differently or omit them

4

variable names are identifiers:

  • letters, digits, underscore; cannot start with a digit
  • Pascal ignores letter case in identifiers
  • use consistent spelling despite this case insensitivity

5

variable holds a value:

  • referring to it in an expression supplies its current value

6

typed variables:

  • each Pascal variable has a declared type
  • its stored values and expressions referring to it have that type
  • in the book's mode, integer ranges from -32768 to 32767

7

declaration and initialization:

  • var x, y: integer; flag: boolean;
  • declarations precede the main body
  • x: integer = 500 supplies an initial value in this dialect
  • explicitly establish a value before reading a variable
  • compiler warnings do not detect every uninitialized read

8

assignment: x := expression

  • evaluate the right-hand side, then store its value in x
  • the old value is replaced
  • successive assignments 25, 36, 49 produce those values when printed
  • x := x + 5 uses the old x to calculate its new value
A three-step swap preserves the first value in temporary storage before overwriting it.
Assignment replaces a stored value. Open full size - Editable SVG

Identifiers and Reserved Words

Identifiers name programs, variables, constants, types, procedures, functions, and fields.

Rules:

Choose names by meaning, not by keyboard convenience.

Detailed notes - 2.2.3: Identifiers and reserved words

1

one naming syntax for different entities:

  • program, variables, and later user-defined entities use identifiers
  • letter/underscore followed by letters, digits, or underscores

2

language also supplies existing words:

  • program, var, begin, end, div, mod
  • write, writeln, integer, boolean

3

reserved words:

  • part of the language grammar
  • cannot be reused as names for program entities

4

predefined identifiers:

  • some built-in names can be hidden by a declaration
  • declaring a variable named integer can hide the type name
  • such reuse makes code confusing and should be avoided

5

classification depends on dialect:

  • historical Pascal and Free Pascal do not classify every built-in word alike
  • do not infer reserved-word status merely from frequent built-in use

Input

read reads values and leaves the rest of the line available. readln reads values and then finishes the current input line.

var
    x, y: integer;
begin
    readln(x, y);
    writeln(x + y);
end.

For simple programs, prefer readln: it usually matches line-oriented input better.

Detailed notes - 2.2.4: Input for later processing

1

input changes variables:

  • obtains data from an external source
  • stores the received values for subsequent processing

2

read(x):

  • reads a value of x's type into x
  • terminal input normally becomes available after Enter
  • square example first reads an integer

3

read -> calculate -> print:

  • x := x*x replaces the input with its square
  • writeln(x) prints the result
  • waiting for input is different from a hung program

4

standard input need not be a keyboard:

  • echo 37 > num.txt creates input data
  • ./square < num.txt reads it and prints 1369
  • changing the file changes the data without changing the program

5

pipes and redirection:

  • echo 37 | ./square supplies another program's output as input
  • > result.txt sends the result to a file
  • shell arranges streams before starting the program
  • program uses standard input/output without needing to know their endpoints

Integer Width

Fixed-size integer types can overflow. If the mathematical result does not fit in the chosen type, the program result is not the mathematical result.

Common Free Pascal integer types:

Type Typical meaning
integer Default signed integer, implementation-dependent size
longint Signed 32-bit integer
int64 Signed 64-bit integer
byte Unsigned 8-bit integer
word Unsigned 16-bit integer

Use a type large enough for all intermediate results, not only for the final answer.

Detailed notes - 2.2.5: Beware insufficient range

1

fixed-width integer overflow:

  • in the book's 16-bit integer mode, 200*200 does not fit
  • the unchecked example produces -25536 instead of 40000

2

bit-level explanation:

  • 40000 - 65536 = -25536
  • the same 16 bits are interpreted as a signed result
  • overflow behavior and checks depend on compiler settings

3

choose a type with enough range:

  • 181^2 fits a signed 16-bit integer; 182^2 does not
  • longint: signed 32-bit, -2^31 through 2^31-1
  • changing the declaration and recompiling extends the usable range
  • 46340^2 fits; 46341^2 exceeds it

4

wider and unsigned types still have limits:

  • int64: signed 64-bit; 3037000499^2 fits
  • qword: unsigned 64-bit, 0 through 2^64-1
  • gains one positive-value bit by giving up negative values
  • (2^32-1)^2 fits qword; (2^32)^2 does not
  • the unchecked example wraps the latter result to zero

Sequential Statements

The simplest program structure is a sequence:

readln(a);
b := a * a;
writeln(b);

Pascal semicolons separate statements. A semicolon before end is usually accepted as an empty extra statement, but a semicolon before else changes the syntax and is normally wrong.

Detailed notes - 2.2.6: A simple statement sequence

1

statements finish before the next one begins:

  • writeln('First'); readln; writeln('Second')
  • readln without arguments consumes the rest of an input line
  • on the terminal it can wait for Enter

2

two pauses in sequence:

  • first Enter permits Second to be printed
  • second Enter permits Third and program termination

3

final readln in some teaching examples:

  • historically used to keep a separately opened console window visible
  • it performs real input; it is not required Pascal boilerplate

4

address window lifetime in the execution environment:

  • launch from an existing terminal or configure the development environment
  • a pause should have an explicit purpose

5

author's concern about teaching through an IDE:

  • one-key execution can conceal compilation and executable files
  • compilation produces a program, as well as reporting errors

6

exercise:

  • print a poem one line at a time
  • wait for Enter between successive lines

7

flowcharts:

  • rectangle: action
  • small circle: start/end in these diagrams
  • diamond: condition
  • arrows show execution order

Branching

Full form:

if x < 0 then
    writeln('negative')
else
    writeln('non-negative');

Without else:

if x = 0 then
    writeln('zero');

Use begin ... end when a branch contains more than one statement:

if x < 0 then begin
    writeln('negative');
    x := -x;
end;
Detailed notes - 2.2.7: Branching

1

useful control flow depends on conditions:

  • select actions, repeat actions, or call other parts of a program

2

branching tests a condition at run time:

  • full branch: one action for true, another for false
  • incomplete branch: action for true, nothing for false

3

if is a statement containing other statements:

  • absolute-value example prints x when x > 0, otherwise -x
  • zero is handled by the second branch

4

whole if/then/else construction = one statement

  • its branch statements are nested inside it

5

condition after if must be boolean:

  • comparison such as x > 0 computes true or false

6

syntax:

  • if condition then statement1
  • optionally add else statement2
  • then separates the condition from its action

7

incomplete-branch version of absolute value:

  • if x < 0 then x := -x;
  • writeln(x) executes afterward in either case
  • mathematical absolute value of the minimum signed integer needs a wider type

8

indent branch contents one level beyond the if:

  • nesting becomes visible without tracing the syntax character by character

9

no semicolon before else:

  • semicolon ends/separates the preceding statement
  • else belongs to the same if and cannot stand alone
Detailed notes - 2.2.8: Compound statements

1

one syntactic statement slot may need several actions

  • for example, an if branch

2

swap example:

  • ensure a <= b by swapping only when a > b
  • temporary t preserves a while its storage is overwritten
  • requires three assignments

3

begin ... end groups statements into one compound statement:

  • t := a; a := b; b := t
  • put this block in the conditional branch

4

book's block layout:

  • begin on the next line, aligned with if
  • body indented one level
  • end aligned with the construction it closes

5

another permitted layout:

  • begin on the same line as then
  • end still aligns with the start of the if
  • matching indentation exposes the full construction

6

third layout:

  • indent begin/end beneath if and the body one level farther
  • author regards this as permissible but does not recommend it

Boolean Expressions

Boolean values have type boolean and values true or false.

Operation Meaning
not Negation
and Conjunction
or Disjunction
xor Exclusive OR
=, <>, <, <=, >, >= Comparisons

Example:

if (x >= 0) and (x <= 100) then
    writeln('inside range');

Parentheses are cheap; use them to make precedence obvious.

Detailed notes - 2.2.9: Boolean expressions and the boolean type

1

comparison operators:

  • >, <, =, <>, >=, <=
  • each computes a boolean result

2

boolean expressions are evaluated like arithmetic expressions:

  • x + 1 produces a number
  • x > 1 produces true or false

3

boolean variable:

  • stores a logical value
  • can be assigned a boolean expression
  • referring to the variable itself supplies a condition

4

example:

  • negative := x < 0;
  • if negative then x := -x

5

logical operators:

  • not: negation; and: conjunction; or: disjunction; xor: exclusive or
  • flag := not flag toggles a boolean
  • parenthesize comparisons: (k >= 0) and (k <= 9)
  • Pascal's logical connectives bind more tightly than comparisons

6

combine conditions:

  • ((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z'))
  • tests ASCII Latin-letter ranges
  • some redundant parentheses can improve readability

7

avoid comparing a boolean to true/false:

  • B instead of B = true
  • not B instead of B = false
  • meaningful names make conditions read naturally: if found then
Section test (1 file) - 2.2.9: Boolean expressions and the boolean type
Section test09 (02-02)In catalog
test.pasPascal / 8 lines
program test;
var
    x: integer;
begin
    x := 0;
    x := not x;
    writeln(x);
end.

Loops

while checks the condition before every iteration:

i := 1;
while i <= n do begin
    writeln(i);
    i := i + 1;
end;

repeat ... until checks the condition after the body, so the body runs at least once:

repeat
    readln(x);
until x >= 0;

for is used when the number of iterations is controlled by an ordinal variable:

for i := 1 to n do
    writeln(i);

for i := n downto 1 do
    writeln(i);

Nested loops solve problems with two or more dimensions, such as tables, matrices, and coordinate grids.

Detailed notes - 2.2.10: Loops; while

1

loop:

  • repeated sequence of actions = body
  • one execution of the body = iteration
  • iteration count may be known in advance, data-dependent, zero, or unbounded

2

loop condition can express:

  • continuation: repeat while true
  • termination: stop when true

3

condition can be implicit:

  • counted loop specifies a control variable and endpoint

4

progress toward termination:

  • some relevant state usually changes between iterations
  • a deliberate infinite loop can use true as its continuation condition

5

while = precondition loop:

  • test before every iteration
  • false ends the loop immediately
  • body may execute zero times

6

syntax: while condition do statement

  • to print twenty lines, count completed iterations
  • initialize i := 0; continue while i < 20

7

compound loop body:

  • print the message, then increment i
  • prepare the first iteration immediately before the loop
  • prepare the next iteration at the end of its body

8

counter invariant:

  • i equals the number of lines already printed
  • printing precedes incrementing because increment records completed work

9

use the counter in the body:

  • start i at 1, continue through i <= 100, print i*i
  • write alone does not separate successive numbers

10

readable output and data-dependent repetition:

  • write(i*i, ' ') inserts a separator
  • writeln after the loop finishes the output line
  • a validation loop may need an unknown number of retries
  • example birth-year bounds are chosen for the book's scenario

11

input validation with while:

  • read year before the loop
  • while outside the accepted interval: report error and read again
  • valid first input gives zero iterations
  • number of invalid attempts has no fixed bound
While can execute zero times; repeat always executes its body before testing its termination condition.
Test before the body or after it. Open full size - Editable SVG
Book examples (3 files) - 2.2.10: Loops; while
Book exampleBook example: diamond.pasIn catalog
diamond.pasPascal / 36 lines
program diamond;
var
    n, k, h, i: integer;
begin
    repeat
        write('Enter the diamond''s height (positive odd): ');
        readln(h)
    until (h > 0) and (h mod 2 = 1);
    n := h div 2;
    for k := 1 to n + 1 do
    begin
        for i := 1 to n + 1 - k do
            write(' ');
        write('*');
        if k > 1 then
        begin
            for i := 1 to 2*k - 3 do
                write(' ');
            write('*');
        end;
        writeln
    end;
    for k := n downto 1 do
    begin
        for i := 1 to n + 1 - k do
            write(' ');
        write('*');
        if k > 1 then
        begin
            for i := 1 to 2*k - 3 do
                write(' ');
            write('*')
        end;
        writeln
    end
end.
Book exampleBook example: hello20.pasIn catalog
hello20.pasPascal / 11 lines
program hello20;
var
    i: integer;
begin
    i := 0;
    while i < 20 do
    begin
        writeln('Hello, world!');
        i := i + 1
    end
end.
Book exampleBook example: star_slash.pasIn catalog
star_slash.pasPascal / 11 lines
program star_slash;
var
    n, m: integer;
begin
    for n := 1 to 24 do
    begin
        for m := 1 to n - 1 do
            write(' ');
        writeln('*')
    end
end.
Detailed notes - 2.2.11: Postcondition loops; repeat

1

while tests before the first iteration

2

repeat ... until condition:

  • executes body before testing
  • body runs at least once
  • condition true ends the loop; false repeats it
  • repeat/until delimit multiple statements without begin/end

3

examples:

  • read a year until it falls within the accepted interval
  • sum := 0; repeatedly read x and add x until sum > 1000
  • choose repeat when the task requires at least one iteration
Detailed notes - 2.2.12: Counted loops; for

1

counted loop:

  • iteration count known on entry
  • control variable enumerates successive values

2

for i := 1 to 20 do statement:

  • visits 1 through 20, inclusive
  • prints the greeting twenty times with a compact loop

3

control-variable rules:

  • body may read i, e.g. write(i*i, ' ')
  • body must not assign to i
  • do not depend on its value after normal completion

4

descending loop:

  • for i := 10 downto 1 do ...
  • to advances; downto retreats by one ordinal value
  • initial/final expressions are evaluated once before iteration
  • later changes to variables used in those expressions do not change the bounds

5

empty interval:

  • to with initial > final performs zero iterations
  • downto with initial < final also performs zero iterations

6

control variable can have an ordinal type:

  • integers, characters, boolean, enumerations, subranges
  • bounds must be compatible with that type
Detailed notes - 2.2.13: Nested loops

1

diagonal of stars:

  • output 24 lines
  • line n contains n-1 spaces followed by '*'

2

outer loop selects the line:

  • for n := 1 to 24
  • inner loop prints its n-1 spaces
  • then print the star and newline

3

use different control variables:

  • inner loop must not alter outer loop's variable
  • inner m ranges from 1 to n-1; first line needs zero iterations
  • next example: outline of a diamond with user-specified height

4

diamond dimensions:

  • height h must be positive and odd
  • h = 2*n+1; top including widest row has n+1 lines

5

analyze top and bottom separately:

  • top: leading spaces decrease, inner spaces increase
  • bottom: reverse those changes

6

leading spaces on top row k:

  • n+1-k; decreases from n to zero

7

spaces between stars:

  • none needed on the first row, which has one star
  • for k > 1: 2*k-3 inner spaces
  • handle k = 1 explicitly

8

row algorithm:

  • print n+1-k spaces and first star
  • if k > 1: print 2*k-3 spaces and second star
  • print newline
  • top uses k = 1 through n+1

9

bottom reuses the same row geometry:

  • visit k from n down to 1
  • widest row is not repeated

10

whole program:

  • repeat input until h > 0 and h mod 2 = 1
  • set n := h div 2
  • print upper and lower portions with their respective outer loops
  • identical row bodies duplicate code
  • corrections would have to be repeated consistently; subprograms will remove this

Bitwise Operations

Free Pascal can apply and, or, xor, and not to integer values as bitwise operations.

Common uses:

On an integer, not inverts every bit, so not 0 is -1 in two's complement:

program test;
var
    x: integer;
begin
    x := 0;
    x := not x;
    writeln(x);
end.
-1
Detailed notes - 2.2.14: Bitwise operations

1

remaining arithmetic facilities:

  • bit operations, named constants, and alternative numeric notation

2

bitwise operations treat integers as fixed-width bit patterns:

  • 16-bit 75 = 0000000001001011

3

not inverts each bit:

  • inversion of that pattern = 1111111110110100
  • signed interpretation: -76; unsigned 16-bit interpretation: 65460

4

and / or / xor act on corresponding pairs of bits:

  • 42 and 166 = 34
  • 42 or 166 = 174
  • 42 xor 166 = 140

5

left shift shl:

  • discard bits leaving the high end; insert zero bits at the low end
  • 1 shl 5 = 32; 21 shl 3 = 168
  • multiplication by 2^k agrees when the result fits the relevant width

6

right shift shr:

  • discard low bits and fill high positions with zero
  • for unsigned/nonnegative values, divides by 2^k and discards remainder
  • negative signed values require care; zero-fill does not preserve their sign
  • Free Pascal supplies separate arithmetic-shift helpers

Named Constants

Use const for values that should not change:

const
    MaxCount = 100;
    NewLine = #10;

Constants make programs easier to read and safer to change.

Detailed notes - 2.2.15: Named constants

1

constant expression has an unchanging value:

  • literal: 37.0
  • compound expression: 6*7

2

compile-time constant:

  • compiler can determine its value while compiling
  • constant arithmetic can be folded to its result

3

run-time constant:

  • logically unchanged, but its value is established at execution time
  • which expressions are accepted at compile time depends on the compiler

4

built-in function does not automatically mean compile-time evaluation:

  • the book's const declaration using copy is rejected

5

named constant:

  • associates an identifier with a compile-time value
  • const declarations belong before the program body
  • keeping configuration constants near the beginning makes them easy to find

6

generalize the repeated-greeting example:

  • message text and repetition count are independent choices
  • changing their literals is easy in a tiny program, harder in a large one

7

give each adjustable value a name:

  • const message = 'Hello, world!'; count = 20;
  • body uses for i := 1 to count do writeln(message)
  • declaration uses =, not :=
  • each name can itself be used in later constant expressions

8

one conceptual value can occur many times:

  • locker count affects allocation, availability totals, and interface bounds
  • editing every repeated literal is error-prone

9

equal numbers may represent unrelated concepts:

  • 26 lockers and 26 printer columns need different names
  • changing one must not silently change the other

10

single source of the value:

  • LockerBoxCount appears numerically only in its declaration
  • all dependent uses follow that definition

11

names also explain meaning:

  • an unexplained 80 gives little information to a reader

12

DefaultHttpPortNumber communicates the role directly:

  • saves readers from reconstructing the meaning from distant code

13

author's style recommendation:

  • name meaningful numeric constants instead of scattering magic numbers
  • simple structural 0, 1, and sometimes -1 commonly remain literal
  • some projects also name all message strings

14

typed constants are a different Pascal facility:

  • const count: integer = 20 specifies storage/type explicitly
  • in some modes they are writable and resemble initialized variables
  • they are not interchangeable with untyped compile-time constants
Book example (1 file) - 2.2.15: Named constants
Book exampleBook example: message_n.pasIn catalog
message_n.pasPascal / 10 lines
program MessageN;
const
    message = 'Hello, world!';
    count = 20;
var
    i: integer;
begin
    for i := 1 to count do
        writeln(message)
end.

Numeric Notation

Free Pascal supports several integer notations:

Form Base
123 Decimal
$7B Hexadecimal
%1111011 Binary
&173 Octal

Use non-decimal notation when the bit pattern is the point of the code.

Detailed notes - 2.2.16: Alternative numeric notation

1

ordinary notation:

  • decimal integers
  • decimal point in floating-point literals

2

hexadecimal integer literal:

  • prefix $; letters A-F are case-insensitive
  • $1A7 = 423

3

Free Pascal also provides:

  • binary %110100111 = 423
  • octal &647 = 423
  • these extensions are not universal across Pascal dialects

4

scientific notation in source:

  • mantissa followed by E and a decimal exponent
  • 7E3 = 7000.0
  • 2.5E-5 = 0.000025

Subprograms

Subprograms give names to parts of an algorithm. They reduce duplication and make a program easier to test.

Detailed notes - 2.3: Subprograms

1

subprogram:

  • separate part of a program solving a subtask
  • has its own body and can have local variables
  • call names the subprogram and supplies parameters

2

reuse:

  • one implementation can be called from many places
  • different parameters adapt it to related cases

3

abstraction matters even for a single call:

  • a meaningful name hides secondary details
  • reader can understand the main algorithm without holding all details in mind

4

Pascal distinguishes:

  • procedure: performs a coherent action; call is a statement
  • function: computes a result; call is an expression

5

dialects and other languages differ:

  • Turbo/Free Pascal permit ignoring a function result in a statement
  • other languages need not make the same procedure/function distinction

6

author's teaching preference:

  • keep actions and value computations visibly separate
  • use this distinction to reason about side effects

Procedures

A procedure performs actions and does not return a value through its name:

procedure PrintStars(n: integer);
var
    i: integer;
begin
    for i := 1 to n do
        write('*');
    writeln;
end;

Call:

PrintStars(10);
Detailed notes - 2.3.1: Procedures

1

procedure declarations precede the main body:

  • SayHello contains writeln('Hello, world!')
  • main body calls SayHello
  • call preserves a return address, transfers control, then resumes after the call

2

procedure structure:

  • header, local declarations, begin ... end body
  • ends with a semicolon, unlike the program's final dot
  • header may declare parameters

3

trivial extraction can add clutter:

  • SayHello illustrates mechanics but gains little clarity over one output statement

4

PrintSpaces(count: integer):

  • count specifies how many spaces to print
  • local i controls for i := 1 to count do write(' ')
  • i and count are private names; outside entities may use the same names

5

procedure call:

  • PrintSpaces(k) prints k spaces
  • name followed by actual arguments in parentheses

6

diamond row needs only two inputs:

  • k: row position in the upper-half geometry
  • n: half-height
  • rendering does not depend on whether the caller is drawing top or bottom

7

PrintLineOfDiamond(k, n):

  • PrintSpaces(n+1-k), first star
  • when k > 1: PrintSpaces(2*k-3), second star
  • newline
  • both outer loops call the same procedure, removing duplicated row code

8

parameter declarations:

  • group same-type names with commas
  • separate groups of different types with semicolons
  • PrintChars(ch: char; count: integer) generalizes PrintSpaces

9

parameterless subprogram:

  • Pascal permits omitting the parameter list and its parentheses

10

terminology:

  • formal parameters: names/types in the declaration
  • actual parameters: arguments supplied at a call
Book example (1 file) - 2.3.1: Procedures
Book exampleBook example: diamondp.pasIn catalog
diamondp.pasPascal / 35 lines
program DiamondProc;

procedure PrintSpaces(count: integer);
var
    i: integer;
begin
    for i := 1 to count do
        write(' ')
end;

procedure PrintLineOfDiamond(k, n: integer);
begin
    PrintSpaces(n + 1 - k);
    write('*');
    if k > 1 then
    begin
        PrintSpaces(2*k - 3);
        write('*')
    end;
    writeln
end;

var
    n, k, h: integer;
begin
    repeat
        write('Enter the diamond''s height (positive odd): ');
        readln(h)
    until (h > 0) and (h mod 2 = 1);
    n := h div 2;
    for k := 1 to n + 1 do
        PrintLineOfDiamond(k, n);
    for k := n downto 1 do
        PrintLineOfDiamond(k, n)
end.

Functions

A function computes a value:

function Square(x: integer): integer;
begin
    Square := x * x;
end;

Call:

writeln(Square(12));

In Pascal, assigning to the function name sets the return value.

Detailed notes - 2.3.2: Functions

1

function is a subprogram returning a value:

  • has header, optional local declarations, and body
  • call can occur within a larger expression

2

Cube example:

  • function Cube(x: real): real;
  • body assigns Cube := x*x*x
  • type after the parameter list specifies the result type

3

function call is a typed expression:

  • Cube(b+3.5) evaluates its argument, runs the function, supplies its result
  • a := Cube(b+3.5) - 17.1 then subtracts and stores the result

4

arguments can be variables or other expressions:

  • a := Cube(a) computes from the old a before replacing it
  • avoid unnecessary run-time work for already known constant results

5

Free Pascal allows discarding a function result:

  • author deliberately avoids this style in the course

6

returning value and control:

  • function must establish the result on every path that returns normally
  • caller receives that result when execution resumes

7

assign to the function's name to set its result:

  • iterative Fibonacci example uses q = 0 and r = 1 initially
  • each iteration: p := q; q := r; r := p+q
  • r holds the current Fibonacci number, q its predecessor
  • iterate from 2 through n; return r; n = 1 needs no iterations

8

separate exceptional/base input:

  • example returns zero for n <= 0
  • author recommends one result-setting assignment on each execution path
  • multiple assignments are permitted by Pascal; this is a style restriction
  • Fibonacci values still must fit the chosen integer type

Boolean Functions

Boolean functions are useful for naming conditions:

function IsDigit(c: char): boolean;
begin
    IsDigit := (c >= '0') and (c <= '9');
end;

Then the main code reads more directly:

if IsDigit(ch) then
    writeln('digit');
Detailed notes - 2.3.3: Boolean functions and conditions

1

boolean-returning function:

  • call itself is a boolean expression
  • can directly serve as an if/while condition
  • a meaningful predicate name can replace a long condition

2

IsLatinLetter(ch):

  • returns membership in 'A'..'Z' or 'a'..'z'
  • use if IsLatinLetter(c) then
  • reusable and clearer than repeated range comparisons
  • comparing the call to true adds nothing

3

return the boolean expression directly:

  • IsDigit := (ch >= '0') and (ch <= '9')
  • if condition then true else false merely reconstructs condition

Value and Variable Parameters

Ordinary parameters receive values. Changing the parameter inside the subprogram does not change the caller's variable.

var parameters receive variables themselves:

procedure Swap(var a, b: integer);
var
    t: integer;
begin
    t := a;
    a := b;
    b := t;
end;

Use var parameters for output parameters or when a procedure must modify the caller-visible object.

Detailed notes - 2.3.4: Variable parameters

1

value parameter:

  • local variable initialized with the evaluated argument
  • p(2*a+7) passes the result, not the expression's constituent storage
  • changing local x does not alter caller's a

2

passing a variable by value still copies its value:

  • p(a) does not create a lasting connection between x and a

3

need for output parameters:

  • one subprogram may calculate several results together
  • x^2, x^3, x^4, x^5 need four successive multiplications
  • independent functions could repeat work

4

variable parameter:

  • formal name refers to the actual variable itself
  • updates through that name change caller's storage

5

var in a parameter declaration:

  • applies to that group up to the next semicolon/closing parenthesis
  • procedure p(var x, y: integer; z: integer; var k: real)
  • x, y, k by reference; z by value

6

powers example:

  • powers(x: real; var quad, cube, fourth, fifth: real)
  • quad := x*x; cube := quad*x; fourth := cube*x; fifth := fourth*x
  • actual output arguments must be variables of the required type
  • arbitrary expressions cannot supply assignable storage

7

call powers(17.5, p, q, r, t):

  • p, q, r, t receive the second through fifth powers

8

variable does not necessarily mean a simple identifier:

  • an array element, record field, or dereferenced pointer can also denote storage

9

passing large objects:

  • a variable parameter avoids copying the whole object
  • useful where copying would be costly

10

file variables have special restrictions:

  • no ordinary assignment, value passing, or function return
  • pass them through variable parameters
Value parameters have independent local storage; variable parameters denote the original variable.
Copy a value or name the caller storage. Open full size - Editable SVG
Detailed notes - 2.6.7: User-defined types and subprogram parameters

1

user-defined parameters require attention to type identity and copying

2

name ordinary parameter/result types first:

  • type MyRange = 1..100; then procedure p1(b: MyRange)
  • an inline 1..100 in that ordinary parameter position is rejected
  • special open-array facilities have their own syntax outside this discussion

3

large value parameters/results can be expensive:

  • copying takes time
  • call-local storage can place pressure on the stack

4

variable parameters avoid copying the object:

  • callee receives access to the original storage through its address
  • requires only pointer-sized call information

5

author's recommendation:

  • avoid unnecessary transfers of large structures
  • when passing them, consider reference-based interfaces
  • where available, read-only reference parameters express nonmutation more accurately

6

size guideline is heuristic:

  • a few machine words differ from hundreds of bytes or kilobytes
  • frequency, target architecture, and compiler behavior determine actual cost

Globals and Side Effects

A global variable is visible outside one subprogram. Globals are sometimes convenient, but they create hidden connections between parts of the program.

Prefer parameters and return values when possible. A function is easiest to understand when the same arguments always produce the same result and no hidden state changes.

Detailed notes - 2.3.5: Global variables

1

scope:

  • local declarations are visible within their subprogram
  • program-level declarations are visible from their declaration onward
  • declare main-body-only data immediately before that body where dialect permits

2

global communication is possible but usually undesirable:

  • subprogram can read/write an earlier program-level variable
  • prefer explicit input parameters, function results, and output parameters

3

hidden state makes calls harder to understand:

  • arguments are visible at the call; global dependencies are not
  • previous activity can change later behavior unexpectedly

4

many potential writers complicate debugging:

  • finding who corrupted a global value can require searching the whole program

5

global singleton data obstructs multiple instances:

  • one game board/database today may become several tomorrow
  • pass the relevant object's state explicitly to support independent instances
Detailed notes - 2.3.6: Functions and side effects

1

Pascal functions can perform more than calculation:

  • read time/input, write output, change globals or variable arguments
  • expression evaluation can therefore alter observable state

2

side effect in the author's expression-focused terminology:

  • observable change occurring during evaluation, beyond its resulting value
  • examples: external variable changes and I/O
  • broader terminology also calls such effects in procedures side effects

3

NegotiateSize function example:

  • prompts until a positive odd height is entered
  • returns height
  • n := NegotiateSize div 2 embeds interactive I/O in an expression

4

make the action explicit with a procedure:

  • NegotiateSize(var res: integer) performs the same dialogue
  • NegotiateSize(n); n := n div 2
  • separates interaction from arithmetic in the caller

5

author's distinction concerns how actions are expressed:

  • ordinary assignment/I/O statements are explicit actions
  • his narrower use of side effect concerns actions hidden inside expressions
  • it does not mean a procedure performing I/O is pure

6

C/C++ make this distinction less syntactically visible:

  • assignment is an expression operation
  • their subprogram syntax does not provide Pascal's procedure category

7

course rule:

  • use expressions primarily to obtain values
  • consciously justified exceptions exist
  • learn to distinguish necessary effects from confusing hidden behavior

Recursion

A recursive subprogram calls itself. Every recursive solution needs:

Example:

function Fact(n: integer): integer;
begin
    if n = 0 then
        Fact := 1
    else
        Fact := n * Fact(n - 1);
end;

Recursion is natural for trees, lists, divide-and-conquer algorithms, and backtracking.

Detailed notes - 2.3.7: Recursion

1

recursive call:

  • direct: a subprogram calls itself
  • indirect: a chain of calls returns to a subprogram already active

2

each invocation has its own locals:

  • allocated for the call, discarded when it returns
  • suspended callers keep their own values

3

termination needs:

  • a simpler instance at each recursive step
  • base case requiring no further recursive call
  • unbounded recursion consumes call storage and can exhaust it

4

recursive PrintChars:

  • count <= 0: do nothing
  • otherwise print one character, call PrintChars(ch, count-1)
  • count 3 produces calls for 3, 2, 1, 0, then returns through them

5

work during unwinding:

  • n mod 10 gives the last digit; n div 10 removes it
  • printing before recursion displays digits backward
  • recurse on n div 10 first, then print n mod 10 to restore normal order
  • zero requires an explicit wrapper case if it must print '0'

6

recursive functions can carry accumulated state:

  • ReverseNumber calls helper with remaining n and accumulator m = 0
  • step: (n div 10, m*10 + n mod 10)
  • base n = 0 returns m
  • 752 -> 257; leading zeroes of the reversed numeral disappear
  • input/result must fit the intended nonnegative integer domain
Printing digits after the recursive call uses suspended frames to restore their original order.
Recursive calls postpone work until return. Open full size - Editable SVG

Program Construction

Structured programming builds programs from:

This is enough for ordinary algorithms. It also keeps reasoning local: the reader can understand one block at a time.

Detailed notes - 2.4: Constructing programs

1

small examples can conceal organizational problems:

  • a screenful of code is comparatively easy to hold in mind

2

larger programs exceed human working memory:

  • experience raises the limit but does not remove it
  • growing software complexity motivated disciplined program structure
Detailed notes - 2.4.1: Structured programming

1

unrestricted jumps entangle control flow:

  • difficult to reconstruct execution paths, even for the author

2

structured-programming foundations:

  • Dijkstra criticized uncontrolled goto use
  • Boehm-Jacopini: sequence, conditional selection, and iteration suffice
  • practical structured constructs have one entry and one exit

3

composition and abstraction:

  • refinement replaces one action by a detailed structured fragment
  • generalization treats such a fragment as one action
  • one entry/exit makes this substitution possible

4

top-down stepwise refinement:

  • begin with the main structure
  • use comments or skeletal subprograms for not-yet-implemented actions
  • replace them progressively, introducing finer subtasks as necessary

5

connection to flowcharts:

  • each temporary action represents a rectangle awaiting refinement
  • the earlier StarSlash example already used this approach

Exits From Loops and Subprograms

Free Pascal provides controlled exits:

Statement Effect
break Leave the nearest loop
continue Start the next loop iteration
exit Leave the current procedure or function

Use these sparingly. They are useful when they remove awkward flags or deeply nested conditions.

Detailed notes - 2.4.2: Early exits

1

clarity is the goal of structural rules:

  • a limited departure can be justified when it makes the program easier to understand

2

early-exit facilities:

  • end a subprogram, program, loop, or iteration
  • modern Pascal dialects provide specific constructs for these purposes

3

exit leaves the current subprogram:

  • handle n <= 0 in Fibonacci, set result, then exit
  • ordinary case follows without enclosing it in else

4

quadratic solver interface:

  • inputs a, b, c
  • outputs success flag and two real roots
  • repeated root can be returned twice

5

guard exceptional cases before normal work:

  • initialize ok := false
  • if a = 0 then exit
  • compute d := b*b-4*a*c; if d < 0 then exit
  • otherwise calculate roots and set ok := true
  • example deliberately rejects linear equations; only read roots when ok

6

guard clauses avoid increasing nesting:

  • normal case stays prominent
  • each rejected special case no longer needs to be considered afterward

7

halt terminates the whole program:

  • callable from inside subprograms
  • use deliberately; a recoverable user mistake should not automatically end everything

8

halt(status):

  • supplies process exit status
  • zero conventionally means success; nonzero indicates failure
  • Unix shell-visible status is normally limited to the low eight bits

9

bare halt:

  • the example treats it as a successful termination
  • explicit status communicates intent more clearly

10

loop exits:

  • break leaves the innermost loop
  • continue skips the remainder of its current iteration
  • useful where they simplify a more complex loop body

Goto

Pascal has labels and goto, but structured alternatives are almost always better. goto destroys the usual block structure and makes the path of control harder to inspect.

Detailed notes - 2.4.3: Unconditional jumps

1

goto label transfers control to a labeled statement:

  • labels can be identifiers or legacy numeric labels
  • meaningful names communicate their destination better

2

declare labels in a label section:

  • label Quit, AllDone, SecondStage;
  • keep labels local to the body where they are used
  • do not use jumps as substitutes for subprogram calls/returns

3

label syntax:

  • point: statement
  • goto point
  • author recommends restricting goto to two particular patterns

4

leave several nested constructs:

  • one forward jump can be clearer than flags checked throughout multiple loops

5

shared cleanup:

  • acquired resources must be released on every relevant exit path
  • early exits otherwise duplicate cleanup code
  • place a cleanup label near the end and jump to it when required

6

both recommended patterns jump forward and outward:

  • backward repetition belongs in a loop
  • jumping into the middle of a construct defeats its entry assumptions

Splitting Into Subprograms

Good reasons to create a subprogram:

Avoid both extremes: one giant program and hundreds of tiny meaningless wrappers.

Etude 2.14 prints a letter Z of stars with a given odd height. Each subprogram has one job: ReadParams validates the argument, PrintLineOfZ draws one row, and PrintChars repeats a character.

Show the complete program
program test;

procedure PrintChars(c: char; n: integer);
var
    i: integer;
begin
    for i := 1 to n do
        write(c);
end;

procedure PrintLineOfZ(i, n: integer);
var
    m: integer;
begin
    m := n div 2 + 1;
    if (i = 1) or (i = m) or (i = n) then
        PrintChars('*', n)
    else
    begin
        PrintChars(' ', n - i);
        PrintChars('*', 1);
    end;
    writeln()
end;

procedure CheckConvert(i, code: integer);
begin
    if (code <> 0) then
    begin
        writeln('Could not convert ', i, ' parameter to number');
        halt(2)
    end;
end;

procedure ReadParams(var n: integer);
var
    e: integer;
begin
    if (ParamCount <> 1) then
    begin
        writeln('Wrong number of parameters, there have to be one of them');
        halt(1)
    end;

    val(ParamStr(1), n, e);
    CheckConvert(1, e);
    if (n <= 5) or (n mod 2 = 0) then
    begin
        writeln('Please enter odd number that is larger than five');
        halt(3)
    end
end;


var
    i, n: integer;
begin
    ReadParams(n);
    for i := 1 to n do
        PrintLineOfZ(i, n);
end.
*******
     *
    *
*******
  *
 *
*******
Detailed notes - 2.4.4: Decomposing a program into subprograms

1

decomposition reduces the amount of detail considered at once

2

one growing main body or subprogram becomes difficult to

navigate/change:

  • small coherent subprograms can simplify even a longer overall source

3

complexity depends on simultaneous mental load:

  • understand one small implementation plus the overall call structure
  • other subprograms can be remembered by their contracts

4

author's size guideline:

  • aim for a body understandable at a glance, often around 25 source rows
  • longer case analysis can be reasonable
  • a growing body is a prompt to look for meaningful subtasks

5

historical basis of the guideline:

  • a conventional terminal displayed about 24/25 rows
  • fitting more text on a larger screen does not remove cognitive limits

6

one subprogram = one identifiable task:

  • split genuinely separable subtasks when they appear

7

false decomposition:

  • moving an arbitrary stretch of code into a new routine adds navigation
  • many shared variables/var parameters can preserve all the original coupling

8

finding boundaries requires practice:

  • two practical rules help test a proposed split

9

one-phrase rule:

  • describe the routine's purpose in one simple phrase
  • purpose plus parameter names should explain its inputs/outputs

10

keep interfaces manageable:

  • author recommends roughly five or fewer parameters as a heuristic
  • long parameter lists increase the effort and error risk of each call

11

independence rule:

  • caller should be understandable without callee's implementation
  • callee should be understandable without caller's implementation
  • constantly reading both bodies together indicates poor separation

12

optional reuse test:

  • imagine using the unchanged routine in a different program
  • plausible reuse is evidence of a coherent independent task
  • inability to reuse it alone does not prove the design bad

Characters and Text Data

Detailed notes - 2.5: Characters, character codes, and text

1

text representation:

  • sequences of character codes
  • encoding assigns numeric representations to characters

2

chapter's simplified model:

  • one byte per character; ASCII and byte-oriented extensions
  • some byte-stream transformations also work on UTF-8
  • general Unicode character processing needs more than this model

Characters and Codes

Values of type char represent characters. Characters are ordinal values: they have codes and an order.

Useful operations:

Operation Meaning
ord(c) Character code
chr(n) Character with code n
succ(c) Next ordinal value
pred(c) Previous ordinal value

Example:

if (c >= 'A') and (c <= 'Z') then
    writeln('uppercase letter');
Detailed notes - 2.5.1: Character facilities in Pascal

1

char stores a single character/code unit in this model:

  • printable characters and control codes
  • useful ASCII codes: NUL 0, BEL 7, BS 8, HT 9, LF 10, CR 13, ESC 27
  • rendering/control behavior depends on the terminal

2

keyboard input and terminal processing:

  • Ctrl combinations can generate control codes
  • terminal driver may interpret them instead of delivering them as data
  • Ctrl-C normally requests interruption, rather than supplying character #3
  • programs can change terminal settings

3

character notation:

  • '7' denotes the digit character
  • #55 denotes the same ASCII code
  • #10 denotes LF; supported caret notation ^J also denotes LF

4

outputting control characters explicitly:

  • write('Hello, world!', #10) supplies a Unix-style newline
  • adjacent literal components can form one string: 'Hello, world!'#10

5

apostrophe inside a literal:

  • double it: 'That''s fine!'
  • four apostrophes denote one apostrophe character

6

character comparisons use ordinal code order:

  • ASCII letter/digit ranges are contiguous
  • (c >= 'a') and (c <= 'z') tests lowercase Latin letters

7

ord and chr:

  • ord(c) obtains a character's numeric code
  • chr(n) constructs the character for a valid code
  • unlike a literal, chr can use a value calculated at run time
  • ASCII display example nests row i and column j loops
  • chr(i*16+j) converts each hexadecimal row/column position to its character
Book example (1 file) - 2.5.1: Character facilities in Pascal
Book exampleBook example: print_ascii.pasIn catalog
print_ascii.pasPascal / 26 lines
program PrintAscii;

var
    i, j: integer;
    c: char;

begin
  write('  |');
  for c := '0' to '9' do
      write(' .', c);
  for c := 'A' to 'F' do
      write(' .', c);
  writeln;
  write('  |');
  for i := 1 to 16 do
      write('---');
  writeln;

  for i := 2 to 7 do
  begin
      write(i, '.|');
      for j := 0 to 15 do
          write('  ', chr(i * 16 + j));
      writeln
  end
end.

Character Input

Character-by-character input is useful for filters:

var
    c: char;
begin
    while not eof do begin
        read(c);
        write(c);
    end;
end.

eof checks end of file. eoln checks end of line.

Detailed notes - 2.5.2: Character-by-character input

1

numeric read can fail on malformed text:

  • default runtime error gives little useful context to a non-programmer

2

{$I-} disables automatic I/O-error handling:

  • IOResult = 0 means success; nonzero reports an I/O error
  • check it promptly; reading IOResult also clears the stored error status
  • a generic parse error still cannot identify the offending input precisely

3

structured input needs informative diagnostics:

  • explain what is wrong and where

4

character-by-character parsing provides control:

  • read raw characters and implement the conversion yourself

5

ReadLongint procedure:

  • isolate the parsing task
  • printing diagnostics inside it simplifies this example but reduces reuse

6

outputs through variable parameters:

  • success: whether a number was read
  • result: meaningful only on success
  • failure leaves result unchanged so caller must test success

7

convert a digit character to its value:

  • ord(c) - ord('0')
  • valid only after checking c is in '0'..'9'

8

decimal accumulation:

  • res starts at zero
  • res := res*10 + digit for each digit, left to right
  • '257' accumulates 0 -> 2 -> 25 -> 257

9

parser mechanics:

  • read(c) with char reads a character
  • skip leading spaces/newlines; track the input position
  • validate each following nonseparator as a digit, then accumulate
  • on invalid character: report position, discard the rest of the line, fail
  • on success: copy res to result, set success true
  • simplified example does not yet handle signs, overflow, every whitespace kind, or EOF

10

caller retries when necessary:

  • read each factor in repeat ... until ok
  • multiply only after both inputs succeeded
  • author contrasts interactive prompts with quiet Unix filter conventions

11

function version can hide work in a loop condition:

  • while not ReadLongint(x) do ; has an empty body
  • input, diagnostics, and output-parameter writes all occur during the test

12

author advises explicit action structure here:

  • compact side-effecting conditions are not automatically clearer

13

general lesson:

  • character-level input and analysis provide the most control over text parsing
Book example (1 file) - 2.5.2: Character-by-character input
Book exampleBook example: char2num.pasIn catalog
char2num.pasPascal / 45 lines
program ReadNumsByChar;

procedure ReadLongint(var success: boolean; var result: longint);
var
    c: char;
    res: longint;
    pos: integer;
begin
    res := 0;
    pos := 0;
    repeat
        read(c);
        pos := pos + 1
    until (c <> ' ') and (c <> #10);
    while (c <> ' ') and (c <> #10) do
    begin
        if (c < '0') or (c > '9') then
        begin
            writeln('Unexpected ``', c, ''''' in pos: ', pos);
            readln;
            success := false;
            exit
        end;
        res := res*10 + ord(c) - ord('0');
        read(c);
        pos := pos + 1
    end;
    result := res;
    success := true
end;

var
    x, y: longint;
    ok: boolean;
begin
    repeat
        write('Please type the first number: ');
        ReadLongint(ok, x)
    until ok;
    repeat
        write('Please type the second number: ');
        ReadLongint(ok, y)
    until ok;
    writeln(x, ' times ', y, ' is ', x * y)
end.

Filters

A filter reads standard input, transforms it, and writes standard output.

Filters should usually avoid prompts, because prompts become part of the output stream.

Detailed notes - 2.5.3: Reading to EOF; filters

1

redirected input and pipes eventually run out of data

2

eof tests end-of-file state:

  • false: another character can be read
  • true: no more data available
  • no argument means standard input

3

EOF is a condition, not an ordinary character in the file:

  • regular-file length is tracked separately by the filesystem

4

no extra data byte must be read as an end marker:

  • eof asks about the stream's state
  • application formats can have sentinels, but those are a different concept

5

filter:

  • reads standard input and produces transformed/analyzed output
  • examples: grep, sort, cut, wc
  • stream interface makes filters composable in pipelines

6

FilterOk:

  • while not eof: read one character
  • on LF, print Ok
  • after the loop, print Good bye
  • counts line terminators; no whole-line storage needed
  • Ctrl-D at an empty terminal input line can signal EOF; Ctrl-C interrupts instead

7

line-length filter:

  • initialize count to zero
  • non-LF increments count
  • LF prints count and resets it
  • example handles newline-terminated lines; an unterminated final fragment needs extra handling
  • next example keeps/discards lines according to their first character

8

three logical states for line selection:

  • undecided, keep, discard
  • an enumeration would express them directly; example uses two booleans

9

on newline:

  • print it only if the current line was selected
  • reset know := false for the next line

10

on the first non-newline character:

  • print := (c <> ' ') and (c <> #9)
  • set know := true

11

after classification:

  • print the character only if print is true
  • remaining characters use the existing decision

12

initial state and self-test:

  • know := false; print := false
  • feeding the program its source retains only unindented nonempty lines

13

terminal buffering:

  • normal terminal mode supplies completed input lines
  • character-by-character processing does not imply one-keystroke-at-a-time interaction

14

storage needs depend on the task:

  • some filters need only a few state variables
  • others need complete lines or much larger datasets
  • sorting can also use external storage when data exceeds memory

This matches Unix pipelines well:

producer | filter | consumer
Book examples (3 files) - 2.5.3: Reading to EOF; filters
Book exampleBook example: filter_len.pasIn catalog
filter_len.pasPascal / 18 lines
program FilterLength;
var
    c: char;
    n: integer;
begin
    n := 0;
    while not eof do
    begin
        read(c);
        if c = #10 then
        begin
            writeln(n);
            n := 0
        end
        else
            n := n + 1
    end
end.
Book exampleBook example: filter_ok.pasIn catalog
filter_ok.pasPascal / 12 lines
program FilterOk;
var
    c: char;
begin
    while not eof do
    begin
        read(c);
        if c = #10 then
            writeln('Ok')
    end;
    writeln('Good bye')
end.
Book exampleBook example: skip_indented.pasIn catalog
skip_indented.pasPascal / 28 lines
program SkipIndented;
var
    c: char;
    know, print: boolean;
begin
    know := false;
    print := false;
    while not eof do
    begin
        read(c);
        if c = #10 then
        begin
            if know and print then
                writeln;
            know := false
        end
        else
        begin
            if not know then
            begin
                print := (c <> ' ') and (c <> #9);
                know := true
            end;
            if print then
                write(c)
        end
    end
end.

Reading Numbers Until EOF

For numeric streams:

var
    x, sum: longint;
begin
    sum := 0;
    while not eof do begin
        read(x);
        sum := sum + x;
    end;
    writeln(sum);
end.

This pattern works well with files and pipelines.

Detailed notes - 2.5.4: Reading numbers to EOF

1

character EOF loop cannot be copied blindly for numeric input

2

example task:

  • count and sum all input integers
  • input length unknown; EOF ends it
  • chosen numeric types must accommodate values and their sum

3

naive pattern:

  • while not eof do read(n), add n, increment count
  • may attempt an extra numeric read after the final actual number

4

numeric reading has several stages:

  • skip leading separators
  • parse the number's characters
  • stop when the representation ends

5

trailing whitespace explains the problem:

  • after the last number, newline/spaces may still remain
  • eof is false although no further number exists
  • the book's runtime example then counts a spurious zero
  • do not equate remaining characters with a valid next number

6

terminal EOF can be transient:

  • later reads may accept more terminal input
  • this differs from repeatedly reading an exhausted ordinary file

7

SeekEof:

  • skips whitespace before testing for exhaustion
  • leaves the next nonwhitespace character available to read

8

use while not SeekEof for whitespace-separated numbers:

  • then read, accumulate, and count
  • malformed numeric tokens still require separate error handling

9

historical Free Pascal problem described by the author:

  • older SeekEof implementations failed on streams such as pipes

10

author's account of its origin:

  • behavior was documented as a limitation rather than promptly corrected

11

2020 investigation:

  • author compared the intended semantics and historical Borland implementation
  • emphasizes testing stream behavior, not only disk-file behavior

12

reported follow-up regression:

  • author says related output buffering changed during the fix

13

version context in the book:

  • corrected SeekEof included in Free Pascal 3.2.2, released in 2021
  • recommendations about available distribution versions reflect the book's date

14

author's conclusion about tool choice:

  • this experience reduced his confidence in Free Pascal for professional work
  • it remains his teaching implementation

15

SeekEoln:

  • skips horizontal whitespace while testing for end of the current line
  • useful for variable-length groups of numbers separated by line boundaries

Pascal Type System

Book examples (2 files) - 2.6: Pascal's type system
Book exampleBook example: a_z.pasIn catalog
a_z.pasPascal / 10 lines
program a_z;
var
    s: string;
    c: char;
begin
    s := '';
    for c := 'A' to 'Z' do
        s := s + c;
    writeln(s)
end.
Book exampleBook example: olympcount.pasIn catalog
olympcount.pasPascal / 37 lines
program OlympiadCounter;
const
    MaxSchool = 67;
    MaxGroup = 100;
type
    CountersArray = array [1..MaxSchool] of integer;
var
    Counters: CountersArray;
    i, c, n: integer;
begin
    for i := 1 to MaxSchool do
        Counters[i] := 0;
    {$I-}
    while not eof do
    begin
        readln(c);
        if IOResult <> 0 then
        begin
            writeln('Incorrect data');
            halt(1)
        end;
        n := c div MaxGroup;
        if (n < 1) or (n > MaxSchool) then
        begin
            writeln('Illegal school id: ', n, ' [', c, ']');
            halt(1)
        end;
        Counters[n] := Counters[n] + 1
    end;
    n := 1;
    for i := 2 to MaxSchool do
        if Counters[i] > Counters[n] then
            n := i;
    for i := 1 to MaxSchool do
        if Counters[i] = Counters[n] then
            writeln(i)
end.

Built-In and User Types

Pascal lets the programmer define new names for types:

type
    Count = longint;
    Index = 1..100;

Types document intent and help the compiler detect mistakes.

Detailed notes - 2.6.1: Built-in and user-defined types

1

built-in types:

  • compiler already knows integer, real, boolean, and similar types

2

user-defined types:

  • programmer introduces a type, usually with a name
  • unnamed types are called anonymous
  • user here means the compiler's user: the programmer

3

type declaration section:

  • starts with type
  • may be global or local to a subprogram
  • scope follows the same broad rules as other declarations

4

type alias:

  • type MyNumber = real;
  • new name for the existing type, compatible with it
  • changing representations separately throughout a large program is error-prone

5

choosing the widest type for everything has costs:

  • may still be insufficient later
  • wastes storage in large structures and can affect performance

6

name a type by its role:

  • type SimObjectId = integer;
  • use SimObjectId wherever an object's identifier is required
  • change its definition once if the identifier range must grow

Subranges and Enumerations

Subrange type:

type
    MonthNumber = 1..12;

Enumeration type:

type
    Color = (Red, Green, Blue);

These are ordinal types: their values have an order and can be used in for loops, arrays, and case statements.

Detailed notes - 2.6.2: Subranges and enumerations

1

aliases add names; subranges/enumerations introduce more specific types

2

subrange:

  • type digit10 = 0..9;
  • restricts values to that interval
  • enable appropriate range checks when run-time validation is needed

3

subrange representation:

  • Free Pascal normally uses an integer representation able to hold its bounds
  • 15000..15010 does not become an offset encoded in a single byte
  • direct representation avoids extra conversion during arithmetic

4

other ordinal subranges:

  • LatinCaps = 'A'..'Z'
  • boundaries must be compile-time constants

5

enumeration:

  • names its possible values explicitly in declaration order
  • RainbowColors = (red, orange, yellow, green, blue, indigo, violet)
  • values can be assigned and compared
  • pred(yellow) = orange; succ(blue) = indigo
  • do not step before the first or after the last value

6

pred/succ also apply to other ordinal types

7

ord gives an enumeration value's ordinal:

  • ordinary enumeration starts at zero and advances by one

8

explicit-number enumeration extensions:

  • dialects can permit them, with additional restrictions
  • author excludes these extensions from the teaching subset

9

value names must not conflict in the same scope:

  • red in both RainbowColors and Signals is ambiguous in the ordinary model
  • prefixes such as RcRed and SigRed distinguish the meanings

Ordinal Types

Ordinal types include integer types, char, boolean, enumerations, and subranges.

Useful operations:

Operation Meaning
ord(x) Numeric position
succ(x) Next value
pred(x) Previous value
low(T) Lowest value of type T
high(T) Highest value of type T

Do not call succ on the last value or pred on the first value.

Enumeration values are ordinal, but they are not numbers. Arithmetic on them does not compile; ord(rc1) * ord(rc2) would multiply their positions instead:

program types;
type
    RainbowColors =
        (red, orange, yellow, green, blue, indigo, violet);
var
    rc1, rc2, rc3: RainbowColors;
begin
    rc1 := green;
    rc2 := yellow;
    rc3 := rc1 * rc2;           { error: no * for an enumeration }
    writeln(rc3);
end.
Detailed notes - 2.6.3: Ordinal types

1

ordinal type has:

  • ordered values with integer ordinal numbers
  • minimum and maximum
  • successor/predecessor except at the respective endpoint
  • ord, succ, pred expose these relationships

2

examples:

  • boolean: false then true
  • char: ordered by codes
  • integer types, enumerations, and ordinal subranges
  • floating-point types do not support this Pascal ordinal interface
  • restrictions on particular constructs/types depend on the dialect

3

ordinal types form a useful language category:

  • subrange definitions and several later constructs require an ordinal type
  • an arbitrary real interval cannot be substituted for one
Section test (1 file) - 2.6.3: Ordinal types
Section test03 (02-06)In catalog
types.pasPascal / 12 lines
program types;
type
    RainbowColors =
        (red, orange, yellow, green, blue, indigo, violet);
var
    rc1, rc2, rc3: RainbowColors;
begin
    rc1 := green;
    rc2 := yellow;
    rc3 := rc1 * rc2;
    writeln(rc3);
end.

Arrays

An array stores elements of one type under indexed positions:

type
    Vector = array[1..100] of integer;
var
    a: Vector;
    i: integer;
begin
    for i := 1 to 100 do
        a[i] := i * i;
end.

The index type is part of the array type. Pascal arrays do not have to start at zero.

Detailed notes - 2.6.4: Arrays

1

structured variable contains component variables:

  • main examples: arrays and records

2

array:

  • elements all have one type
  • index selects an element: a[3]
  • index may be an expression evaluated at run time

3

named array type:

  • real100 = array [1..100] of real
  • a, b: real100 creates two arrays of that type
  • a[1] := 1; a[i] := a[i-1]/2 builds powers of one half
  • b[i] := sin(a[i]) builds corresponding sine values
  • whole-array assignment copies all components; account for its cost
  • use a shared named type when compatible arrays are required

4

anonymous array declarations:

  • a and b declared together share their anonymous type
  • a separately repeated declaration can create a distinct type
  • structural similarity does not guarantee compatibility in every Pascal dialect

5

index specification is an ordinal type:

  • 1..100 is an anonymous subrange
  • a named subrange or enumeration can be used instead
  • array [RainbowColors] counts objects by color
  • array [char] counts byte characters
  • array [boolean] gives two entries for a condition's two outcomes

6

initialization and component variables:

  • array initializer lists values in parentheses
  • each a[i] is a real variable, usable as a var argument
  • components also have addresses

7

olympiad example:

  • many counters of the same type, one per school
  • card number's leading digits identify school; last two identify pupil
  • input line holds card number plus name; names are irrelevant to the count
  • readln reads the number and discards the rest of the line
  • redirect olymp.txt to standard input

8

data and first pass:

  • MaxSchool = 67; MaxGroup = 100; Counters[1..MaxSchool]
  • initialize every counter to zero
  • read each record with I/O checking handled explicitly
  • school number n := card div MaxGroup

9

validate index before indexing:

  • require 1 <= n <= MaxSchool
  • invalid input must not access nonexistent array storage
  • checked builds detect range errors; unchecked access may corrupt memory

10

failure and result computation:

  • report invalid data/school and stop with a failure status
  • valid record increments Counters[n]
  • second pass keeps index n of the largest counter seen so far
  • initialize n := 1; update when Counters[i] > Counters[n]
  • third pass prints every i whose count equals Counters[n]
  • prints ties, not just the first winning school
  • with no participants, all zero counters tie under this algorithm
An array has homogeneous indexed components; a record has named fields that can have different types.
Index an array; name a record field. Open full size - Editable SVG

Records

A record groups fields of possibly different types:

type
    Date = record
        day: 1..31;
        month: 1..12;
        year: integer;
    end;
var
    d: Date;
begin
    d.day := 14;
    d.month := 6;
    d.year := 2026;
end.

Arrays and records combine naturally:

type
    Student = record
        name: string;
        score: integer;
    end;
    Group = array[1..30] of Student;
Detailed notes - 2.6.5: Records

1

record:

  • named fields, potentially of different types
  • array elements instead share one type and are selected by index

2

CheckPoint example:

  • n and penalty: integers
  • latitude and longitude: real numbers
  • hidden: boolean
  • record ... end declares the fields
  • cp.latitude selects a field using a dot
  • whole-record assignment copies the record
  • fields are variables and can be assigned/passed by reference
  • storage may include alignment padding as well as the field contents
Detailed notes - 2.6.6: Combining data structures

1

nest records and arrays:

  • record may contain arrays or records
  • CheckPointArray = array [1..MaxCheckPoint] of CheckPoint
  • track[7].latitude selects one field of one array element
  • corresponds to a row/column cell in a conceptual table

2

multidimensional array = array of arrays:

  • array [1..5, 1..7] of integer
  • equivalent nesting: array [1..5] of array [1..7] of integer
  • a[2,6] and a[2][6] select the same component
  • matrices are a natural application
  • large nested structures consume real storage; local arrays can exhaust stack space

Type Conversions

Common conversions:

Operation Meaning
ord(c) Character or enum to number
chr(n) Number to character
trunc(x) Real to integer by discarding fractional part
round(x) Real to nearest integer

Avoid conversions that only silence the compiler. A conversion should express a real change of representation.

Detailed notes - 2.6.8: Type conversion

1

integer value can be assigned to real:

  • r := 15 gives floating-point 15.0

2

conversion changes representation:

  • integer bits cannot simply be copied as a floating-point encoding
  • compiler generates the required representation conversion

3

implicit conversions:

  • occur without an explicit request in source
  • supported numeric assignments and value arguments may convert types
  • narrowing range/precision still needs care

4

floating-point to integer requires a chosen operation:

  • trunc discards the fraction toward zero
  • round rounds to an integer according to the rounding behavior
  • example: 15.75 -> trunc 15, round 16
  • default nearest-even behavior resolves exact halfway cases in the discussed environment

5

values can be converted; var arguments cannot be silently replaced by

converted copies:

  • callee operates on the original object's representation
  • actual variable type must meet the declared var-parameter requirements

6

explicit cast syntax: TypeName(expression)

  • e.g. byte('5') obtains an ordinal representation
  • some casts reinterpret equal-sized storage, others convert ordinal values
  • writable reinterpretations require compatible storage sizes

7

prefer purpose-specific operations:

  • ord for character code, chr for code-to-character
  • use casts only when their exact representation effect is understood

Character Arrays and String Literals

A string literal is a sequence of characters in apostrophes:

writeln('abc');

An array of char is a fixed-size sequence:

type
    Buffer = array[1..80] of char;

This is useful when the size is part of the format.

Detailed notes - 2.6.9: String literals and char arrays

1

string literals appeared first as immediately printed text

2

text is a broadly useful representation of information:

  • author emphasizes its suitability for many structured datasets
  • sampled images/audio/video often use more suitable binary encodings

3

whole-string operations can be clearer than manual character processing

4

char arrays can hold text:

  • Pascal permits certain special operations, including assignment from a literal
  • assigning a 13-character greeting to char[30] leaves zero padding
  • printing the array can emit all 30 bytes, including invisible NULs

5

padding explains the unexpected output:

  • useful characters occupy the initial elements
  • remaining elements receive zero characters in the example

6

manual output can stop at #0:

  • inspect elements in a bounded loop; break at the terminator
  • works here but makes a simple string action cumbersome

7

strings need a current length distinct from capacity:

  • actual input length is unknown when the program is written
  • concatenation and appending characters are common operations

8

later Pascal dialects supply dedicated string types for these tasks

9

literal components can include control codes:

  • 'one'#9'two' contains a tab between the words
  • alternate quoted text and # codes to construct one literal
  • supported caret notation can represent corresponding control characters too

string

Free Pascal provides a string type for text:

var
    s: string;
begin
    readln(s);
    writeln(length(s));
end.

String positions are indexed from 1.

Common string operations:

Operation Meaning
length(s) String length
s[i] Character at position i
copy(s, start, count) Substring
pos(substr, s) Search
delete(s, start, count) Remove part
insert(part, s, pos) Insert part
val(s, x, code) Convert text to number
str(x, s) Convert number to text
Detailed notes - 2.6.10: The string type

1

short strings used in the book:

  • string[15] holds at most 15 characters
  • plain string in the selected mode means capacity 255
  • one byte records current length
  • plain string can mean a different string family under other compiler modes/settings

2

short-string storage:

  • capacity plus one byte
  • meaningful characters indexed 1 through length(s)
  • s[0] is the length byte viewed as char; prefer length(s) over ord(s[0])
  • positions beyond current length are not meaningful string contents

3

assignment between capacities:

  • permitted for these string types
  • assigning a longer value to a smaller capacity truncates it

4

copying uses the meaningful contents:

  • maximum reserved capacity and current useful data are different quantities

5

short-string var parameters have special compatibility rules:

  • differently declared capacities can be accepted in some interfaces/settings
  • caller's actual capacity must still be respected

6

  • concatenates strings:
  • 'abra' + 'kadabra' = 'abrakadabra'

7

empty string:

  • '' has length zero
  • ' ' contains one space and has length one

8

char can become a one-character string:

  • s := ''; then s := s+c appends each character
  • looping c from 'A' to 'Z' builds the alphabet

9

other Free Pascal string families:

  • managed long strings and Unicode-related representations exist
  • their limits/storage behavior differ from these short strings
Detailed notes - 2.6.11: Built-in string operations

1

built-ins simplify common tasks:

  • character-level processing remains sufficient to implement the basic operations

2

length and SetLength:

  • length(s) returns current length
  • shortening 'abrakadabra' to four characters gives 'abra'
  • when extending a short string, initialize the newly meaningful characters
  • changing its length does not increase its declared capacity

3

course exercise:

  • understand how the operations below work on characters before relying on them

4

LowerCase / UpCase:

  • return corresponding lowercase/uppercase Latin-letter forms in this discussion
  • full locale/Unicode case conversion requires more care

5

copy(source, start, count):

  • returns the requested substring, shortened at the end if necessary
  • copy('abrakadabra', 3, 4) = 'raka'

6

delete(s, start, count):

  • removes characters in place
  • delete(s, 5, 4) changes 'abrakadabra' to 'abrabra'

7

insert(piece, s, position):

  • modifies destination s
  • inserting 'PQR' at position 4 of 'abcdef' gives 'abcPQRdef'

8

pos(piece, source):

  • first matching position; zero means absent
  • pos('kada', 'abrakadabra') = 5

9

val(text, number, error_position):

  • converts a numeric representation
  • error_position = 0 indicates success
  • otherwise reports the offending position; do not use number as a valid result

10

str(number, destination):

  • writes formatted numeric text into a string
  • formatting resembles write: str(12.5:9:3, s)
  • result is three spaces followed by 12.500

11

BinStr / OctStr / HexStr:

  • integer-to-string functions for binary, octal, hexadecimal
  • arguments specify the number and desired output width

Command-Line Arguments

Free Pascal exposes command-line arguments through:

Function Meaning
paramcount Number of arguments
paramstr(i) Argument i; paramstr(0) is the program name

Example:

if paramcount <> 1 then begin
    writeln('usage: program filename');
    halt(1);
end;
Detailed notes - 2.6.12: Command-line arguments

1

program can receive arguments at startup:

  • ./demo abra schwabra kadabra supplies three arguments

2

ParamCount and ParamStr:

  • ParamCount excludes the program's own name
  • ParamStr(i) obtains argument i, numbered from 1
  • ParamStr(0) provides the runtime's program-name/path value

3

display example:

  • loop i := 0 to ParamCount and print ParamStr(i)
  • shell quoting such as "one two three" passes one argument
  • grouping is performed by the shell before Pascal receives the arguments
Book example (1 file) - 2.6.12: Command-line arguments
Book exampleBook example: cmdline.pasIn catalog
cmdline.pasPascal / 7 lines
program cmdline;
var
    i: integer;
begin
    for i := 0 to ParamCount do
        writeln('[', i, ']: ', ParamStr(i))
end.

Case Statement

case selects one branch by an ordinal value:

case ch of
    '0'..'9':
        writeln('digit');
    'A'..'Z', 'a'..'z':
        writeln('letter');
else
    writeln('other');
end;

Use case when one expression is compared with several constant alternatives. Use if when conditions are heterogeneous or depend on complex predicates.

Detailed notes - 2.7: The case statement

1

case generalizes conditional selection:

  • evaluate an ordinal expression
  • select a branch according to its value

2

syntax:

  • case expression of ... end
  • each branch: value_set: statement
  • statement may be compound
  • optional else handles values absent from the other branches

3

branch labels:

  • one constant, comma-separated constants, or a constant range
  • values must be determined at compile time

4

character-classification example:

  • letter ranges, digit range, arithmetic signs, comparison signs
  • separate cases for spaces, control characters, brackets, and quotes
  • else handles unclassified input

5

unexplained numeric alternatives obscure meaning:

  • case nv of 1, 2, 3 ... forces readers to reconstruct each number's role
  • easy to select the wrong number elsewhere in the program

6

prefer a meaningful enumeration for conceptual alternatives:

  • names convey which state/category each branch handles

7

keep branch implementations manageable:

  • case may justify a somewhat longer subprogram
  • extract complex alternatives into coherent routines
  • author's style discourages deeply nested case constructions
Book example (1 file) - 2.7: The case statement
Book exampleBook example: case.pasIn catalog
case.pasPascal / 34 lines
program SymbolType;
var
    c: char;
begin
    read(c);
    write('The symbol is ');
    case c of
        'a'..'z', 'A'..'Z':
            writeln('a latin letter');
        '0'..'9':
            writeln('a digit');
        '+', '-', '/', '*':
            writeln('an arithmetic operation symbol');
        '<', '>', '=':
            writeln('a comparision sign');
        '.', ',', ';', ':', '!', '?':
            writeln('a punctuation symbol');
        '_', '~', '@', '#', '$', '%', '^',
        '&', '`', '|', '\':
            writeln('a special purpose sign');
        ' ':
            writeln('the space character');
        #9, #10, #13:
            writeln('a formatting code');
        #27:
            writeln('the escape code');
        '(', ')', '[', ']', '{', '}':
            writeln('a grouping symbol');
        '"', '''':
            writeln('a quoting symbol');
        else
            writeln('something strange')
    end
end.

Full-Screen Programs

Free Pascal can use the crt unit for terminal-style full-screen interaction:

uses crt;

begin
    clrscr;
    gotoxy(10, 5);
    textcolor(lightgreen);
    writeln('Hello');
end.

Common crt tools:

Tool Meaning
clrscr Clear screen
gotoxy(x, y) Move cursor
whereX, whereY Current cursor position
keypressed Whether a key is waiting
readkey Read one key
textcolor, textbackground Change colors
delay(ms) Pause

Dynamic input reads keys as events rather than waiting for a whole line. This is useful for simple games and interactive demos, but terminal behavior can depend on the environment.

Detailed notes - 2.8: Full-screen programs

1

optional practical detour:

  • these terminal facilities are not prerequisites for later chapters

2

self-chosen projects matter:

  • more available techniques make personally interesting projects possible

3

full-screen text interfaces:

  • use terminal positions and immediate key input
  • go beyond ordinary line-oriented dialogue

4

text interfaces can support substantial applications:

  • editors, mail/chat clients, and games such as NetHack

5

dynamic terminal games are one possible application

  • usefulness is broader than games

6

reading strategy:

  • skip if already working on an interesting project that does not need these tools
  • otherwise experiment for possible project ideas
Book example (1 file) - 2.8: Full-screen programs
Book exampleBook example: colordemo.pasIn catalog
colordemo.pasPascal / 56 lines
program ColorsDemo;
uses crt;

const
    ColorCount = 16;
    BGColCount = 8;
var
    AllColors: array [1..ColorCount] of word =
    (
        Black, Blue, Green, Cyan,
        Red, Magenta, Brown, LightGray,
        DarkGray, LightBlue, LightGreen, LightCyan,
        LightRed, LightMagenta, Yellow, White
    );

procedure MakeLine(line: integer; fgcolor: word);
var
    i, w, cw: integer;
begin
    w := ScreenWidth;
    cw := w div BGColCount;
    if cw = 0 then
        cw := 1;
    if line = ScreenHeight then
        w := w - 1;
    for i := 1 to w do
    begin
        GotoXY(i, line);
        TextBackground(AllColors[(i-1) div cw + 1]);
        if i mod 2 = 0 then
            TextColor(fgcolor + blink)
        else
            TextColor(fgcolor);
        write('*')
    end
end;

procedure MakeScreen;
var
    i: integer;
begin
    clrscr;
    for i := 1 to ScreenHeight do
        MakeLine(i, AllColors[i mod ColorCount + 1])
end;

var
    SaveTextAttr: integer;
begin
    SaveTextAttr := TextAttr;
    MakeScreen;
    readln;
    {write(#27'[0m');}
    TextAttr := SaveTextAttr;
    clrscr
end.
Detailed notes - 2.8.1: Background

1

escape sequences control terminals:

  • byte sequences commonly beginning with ESC, code 27
  • move cursor, set attributes, scroll, and perform other screen actions

2

full-screen input also needs terminal-mode changes:

  • canonical mode delivers completed lines
  • Ctrl-C/Ctrl-D normally receive special driver treatment
  • applications can configure these behaviors

3

terminal differences motivate libraries:

  • libraries hide differing control sequences/capabilities
  • ncurses is a common C example

4

crt history:

  • originated in Borland Pascal's DOS environment
  • Free Pascal implements a compatible interface using host-system facilities

5

crt is the simpler interface chosen for these teaching examples

6

import it with uses crt:

  • placed after the program header
  • startup changes terminal behavior
  • provide an explicit way to exit; familiar interrupt keys may behave differently

7

crt assumes an interactive terminal:

  • do not treat these examples as ordinary redirectable stream filters
Detailed notes - 2.8.2: Output at arbitrary screen positions

1

clrscr:

  • clears the screen and moves cursor to the upper-left corner

2

GotoXY(x, y):

  • horizontal position first, vertical position second
  • upper-left cell is (1,1)
  • ScreenWidth / ScreenHeight provide terminal dimensions known to crt

3

centered greeting example:

  • clear, position cursor, print message
  • move cursor out of the way, delay, clear again
  • delay takes milliseconds; 5000 means five seconds

4

centering uses integer arithmetic:

  • horizontal unused width = screen width - message length
  • distribute that space around the message
  • with one-based coordinates, add 1 to the left/top margin count
  • handle messages wider than the available screen

5

complete sequence and position queries:

  • keep message/delay as named constants
  • WhereX / WhereY return current cursor position
  • output itself advances the cursor
  • do not pass coordinates outside the available cells

6

resize limitation described for this crt interface:

  • dimensions established at startup may not track later window resizing
Book example (1 file) - 2.8.2: Output at arbitrary screen positions
Book exampleBook example: hellocrt.pasIn catalog
hellocrt.pasPascal / 17 lines
program HelloCrt;
uses crt;
const
    TheMessage = 'Hello, world!';
    DelayDuration = 5000;   { 5 seconds }
var
    x, y: integer;
begin
    clrscr;
    x := (ScreenWidth - length(TheMessage)) div 2;
    y := ScreenHeight div 2;
    GotoXY(x, y);
    write(TheMessage);
    GotoXY(1, 1);
    delay(DelayDuration);
    clrscr
end.
Detailed notes - 2.8.3: Immediate keyboard input

1

KeyPressed:

  • true when an unread key code is available
  • false when no input is waiting

2

ReadKey:

  • removes and returns the next key code
  • blocks until input exists if none is available
  • consumes input, so its call has an observable effect

3

ordinary keys return char codes:

  • letters/digits/punctuation usually return their characters
  • Enter is #13 in the illustrated crt implementation
  • Escape #27, Tab #9, Backspace #8
  • terminal/platform differences should be checked

4

extended key protocol:

  • first ReadKey returns #0
  • second ReadKey returns the special-key code
  • arrows: left 75, right 77, up 72, down 80
  • a small key-code display program reveals the actual environment's behavior

5

historical implementation irregularities:

  • author observed some unexpected multi-code sequences
  • these observations belong to the version/environment used for the book

6

GetKey wrapper isolates the protocol:

  • one place calls ReadKey and handles the optional second read
  • caller sees one explicit input operation
  • wrapping changes interface clarity, not the underlying fact that input is consumed

7

GetKey(var code: integer):

  • ordinary key -> ord(c)
  • extended key -> negative ordinal of the second code
  • negative/positive values distinguish categories
  • use it to build a greeting moved by arrow keys

8

separate drawing operations:

  • ShowMessage prints at current coordinates
  • HideMessage replaces it with the same number of spaces
  • MoveMessage hides, adds dx/dy to coordinates, then redraws
  • use named constants for arrow codes

9

input loop for the greeting:

  • ordinary key exits
  • arrow selects the corresponding movement; other extended keys do nothing
  • initial example omits bounds checks; add them to prevent off-screen coordinates

10

moving-star example:

  • arrow starts/changes continuous movement
  • space stops; Escape exits

11

wrap at screen edges:

  • beyond right -> left; beyond left -> right
  • analogous wrapping vertically

12

timing:

  • 100 ms between steps gives roughly ten moves per second

13

group star state in one record:

  • position CurX/CurY and direction dx/dy
  • ShowStar, HideStar, MoveStar operate on that state
  • MoveStar erases, advances, wraps, and redraws
  • SetDirection changes the velocity components

14

main loop:

  • initialize centered position and zero direction
  • no waiting key: move, delay, continue to next iteration
  • waiting key: read and dispatch it
  • space sets both direction components to zero
  • Escape breaks the loop; clear the screen before finishing
Book examples (4 files) - 2.8.3: Immediate keyboard input
Book exampleBook example: getkey.pasIn catalog
getkey.pasPascal / 28 lines
program GtKey;
uses crt;

procedure GetKey(var code: integer);
var
    c: char;
begin
    c := ReadKey;
    if c = #0 then
    begin
        c := ReadKey;
        code := -ord(c)
    end
    else
    begin
        code := ord(c)
    end
end;


var
    i: integer;
begin
    repeat
        GetKey(i);
        writeln(i)
    until i = ord(' ')
end.
Book exampleBook example: movehello.pasIn catalog
movehello.pasPascal / 77 lines
program MovingHello;
uses crt;
const
    KeyLeft  = -75;
    KeyRight = -77;
    KeyUp    = -72;
    KeyDown  = -80;
    TheMessage = 'Hello, world!';

procedure GetKey(var code: integer);
var
    c: char;
begin
    c := ReadKey;
    if c = #0 then
    begin
        c := ReadKey;
        code := -ord(c)
    end
    else
    begin
        code := ord(c)
    end
end;

procedure ShowMessage(x, y: integer; msg: string);
begin
    GotoXY(x, y);
    write(msg);
    GotoXY(1, 1)
end;

procedure HideMessage(x, y: integer; msg: string);
var
    len, i: integer;
begin
    len := length(msg);
    GotoXY(x, y);
    for i := 1 to len do
        write(' ');
    GotoXY(1, 1)
end;

procedure MoveMessage(var x, y: integer; msg: string; dx, dy: integer);
begin
    HideMessage(x, y, msg);
    x := x + dx;
    y := y + dy;
    ShowMessage(x, y, msg)
end;

var
    CurX, CurY: integer;
    c: integer;
begin
    clrscr;
    CurX := (ScreenWidth - length(TheMessage)) div 2;
    CurY := ScreenHeight div 2;
    ShowMessage(CurX, CurY, TheMessage);
    while true do
    begin
        GetKey(c);
        if c > 0 then         { non-extended code; quit }
            break;
        case c of
            KeyLeft:
                MoveMessage(CurX, CurY, TheMessage, -1, 0);
            KeyRight:
                MoveMessage(CurX, CurY, TheMessage, 1, 0);
            KeyUp:
                MoveMessage(CurX, CurY, TheMessage, 0, -1);
            KeyDown:
                MoveMessage(CurX, CurY, TheMessage, 0, 1)
        end
    end;
    clrscr
end.
Book exampleBook example: movingstar.pasIn catalog
movingstar.pasPascal / 99 lines
program MovingStar;
uses crt;
const
    KeyLeft   = -75;
    KeyRight  = -77;
    KeyUp     = -72;
    KeyDown   = -80;
    KeyEscape =  27;
    DelayDuration = 100;

procedure GetKey(var code: integer);
var
    c: char;
begin
    c := ReadKey;
    if c = #0 then
    begin
        c := ReadKey;
        code := -ord(c)
    end
    else
    begin
        code := ord(c)
    end
end;

type
    star = record
        CurX, CurY, dx, dy: integer;
    end;

procedure ShowStar(var s: star);
begin
    GotoXY(s.CurX, s.CurY);
    write('*');
    GotoXY(1, 1)
end;

procedure HideStar(var s: star);
begin
    GotoXY(s.CurX, s.CurY);
    write(' ');
    GotoXY(1, 1)
end;

procedure MoveStar(var s: star);
begin
    HideStar(s);
    s.CurX := s.CurX + s.dx;
    if s.CurX > ScreenWidth then
        s.CurX := 1
    else
    if s.CurX < 1 then
        s.CurX := ScreenWidth;
    s.CurY := s.CurY + s.dy;
    if s.CurY > ScreenHeight then
        s.CurY := 1
    else
    if s.CurY < 1 then
        s.CurY := ScreenHeight;
    ShowStar(s)
end;

procedure SetDirection(var s: star; dx, dy: integer);
begin
    s.dx := dx;
    s.dy := dy
end;

var
    s: star;
    c: integer;
begin
    clrscr;
    s.CurX := ScreenWidth div 2;
    s.CurY := ScreenHeight div 2;
    s.dx := 0;
    s.dy := 0;
    ShowStar(s);
    while true do
    begin
        if not KeyPressed then
        begin
            MoveStar(s);
            delay(DelayDuration);
            continue
        end;
        GetKey(c);
        case c of
            KeyLeft:   SetDirection(s, -1,  0);
            KeyRight:  SetDirection(s,  1,  0);
            KeyUp:     SetDirection(s,  0, -1);
            KeyDown:   SetDirection(s,  0,  1);
            ord(' '):  SetDirection(s,  0,  0);
            KeyEscape: break
        end
    end;
    clrscr
end.
Book exampleBook example: rdkey.pasIn catalog
rdkey.pasPascal / 13 lines
program RdKey;
uses crt;
var
    c, cc: char;
begin
    repeat
        c := ReadKey;
        cc := c;
        if (cc < #32) or (cc > #126) then
            cc := '?';
        writeln(ord(c), ' (', cc, ')')
    until c = ' '
end.
Detailed notes - 2.8.4: Color control

1

terminals can choose foreground and background colors

2

crt exposes a historically limited attribute model:

  • sixteen foreground colors, eight background colors, blink flag
  • inherited from the DOS text-screen interface

3

compatibility explains the limits:

  • other interfaces can expose wider terminal capabilities
  • author keeps crt here because it is easy to learn

4

TextColor / TextBackground:

  • named color constants select subsequent output attributes
  • TextColor(Yellow); TextBackground(Blue) gives yellow text on blue
  • TextColor(Blue or Blink) requests blinking blue text where supported

5

restore attributes before exit:

  • save TextAttr before changing colors
  • restore it at the end, then perform output such as clrscr to apply it

6

terminal escape reset:

  • write(#27'[0m') requests default display attributes
  • this is direct terminal control rather than a crt color call

7

color demonstration:

  • foreground varies by row
  • background varies across groups of columns
  • alternating positions request blink

8

decomposition:

  • AllColors stores named color values
  • MakeScreen chooses row foreground and calls MakeLine
  • MakeLine computes background groups and outputs stars
  • keep group width at least one; avoid final bottom-right cell to prevent scrolling

9

pause so the result remains visible:

  • readln waits for Enter in this demonstration

10

main sequence and indexing:

  • save attributes, draw, wait, restore, clear
  • mod cycles through foreground entries
  • div maps columns to background groups
  • bound the background index for widths not divisible by eight
  • the printed sample's simple division formula needs that edge-case correction

Pseudorandom Numbers

Use randomize once at program start, then call random:

randomize;
writeln(random(6) + 1);  { 1..6 }

Pseudorandom numbers are deterministic sequences initialized by a seed.

Detailed notes - 2.8.5: Random and pseudorandom numbers

1

terminal tools make simple games feasible

2

author encourages projects that make programming enjoyable:

  • his claim linking interest in games to suitability for programming is a personal view

3

random choices provide variety:

  • even a deterministic game can vary equivalent choices between sessions

4

security-sensitive randomness needs unpredictability:

  • operating systems provide facilities drawing on entropy and maintained state
  • ordinary demonstration generators are unsuitable for secret keys

5

ordinary visual/game demonstrations often need only pseudorandom variation

  • security, adversarial, or money-related uses require stronger requirements

6

pseudorandom generator:

  • maintains internal state
  • deterministic update produces the next state and result

7

seed controls repeatability:

  • same initial state and call sequence reproduce the results
  • useful for debugging
  • varying startup seed changes the demonstration between runs

8

randomize initializes generator state:

  • call once near startup when varying runs is wanted
  • repeatedly reseeding can repeat or correlate results

9

random forms:

  • random -> floating-point value in [0,1)
  • random(n) -> integer in 0..n-1 for positive n
  • obtaining a value advances generator state

10

random-stars demonstration:

  • choose x := random(ScreenWidth)+1 and analogous y
  • skip bottom-right cell to avoid scrolling
  • select a random color, draw '*', delay 20 ms
  • continue until a key is waiting
  • restore original text attributes and clear on exit
Book example (1 file) - 2.8.5: Random and pseudorandom numbers
Book exampleBook example: randstars.pasIn catalog
randstars.pasPascal / 37 lines
program RandomStars;
uses crt;

const
    DelayDuration = 20;
    ColorCount = 16;
var
    AllColors: array [1..ColorCount] of word =
    (
        Black, Blue, Green, Cyan,
        Red, Magenta, Brown, LightGray,
        DarkGray, LightBlue, LightGreen, LightCyan,
        LightRed, LightMagenta, Yellow, White
    );

var
    x, y, col: integer;
    SaveTextAttr: integer;
begin
    randomize;
    SaveTextAttr := TextAttr;
    clrscr;
    while not KeyPressed do
    begin
        x := random(ScreenWidth) + 1;
        y := random(ScreenHeight) + 1;
        if (x = ScreenWidth) and (y = ScreenHeight) then
            continue;
        col := random(ColorCount) + 1;
        GotoXY(x, y);
        TextColor(AllColors[col]);
        write('*');
        delay(DelayDuration)
    end;
    TextAttr := SaveTextAttr;
    clrscr
end.

Files

General Pattern

A file variable connects program code to an external file:

var
    f: text;
begin
    assign(f, 'data.txt');
    reset(f);        { open existing file for reading }
    { read from f }
    close(f);
end.

Opening modes:

Procedure Meaning
reset(f) Open existing file for reading
rewrite(f) Create/truncate file for writing
append(f) Open text file for appending
close(f) Finish work with the file
Detailed notes - 2.9.1: General principles

1

programs can open files themselves:

  • not limited to streams arranged by shell redirection
  • operating-system permissions still apply

2

opening a file:

  • identify its path and intended access mode
  • obtain an associated stream for subsequent operations

3

file variables identify active streams:

  • special types with restricted operations
  • no ordinary assignment or independent file-value expressions
  • pass file variables through var parameters

4

three interfaces:

  • text: textual input/output
  • file: untyped block I/O
  • file of T: fixed-size values represented as T
  • selected interface reflects the operation the program needs

5

assign(f, filename):

  • associates a path with a file variable
  • does not open/create the file or check existence
  • filename may be calculated at run time
  • Unix leading / means absolute path; otherwise relative to current directory

6

filename belongs to the filesystem:

  • program may obtain it from arguments, input, or another file

7

file-variable name belongs to source code:

  • arbitrary identifier, independent of disk filename

8

assign establishes the association:

  • a closed file variable can later be assigned another path

9

opening operations:

  • reset: open existing file from its beginning
  • rewrite: create or truncate to an empty file
  • append: open text output at its end
  • actual read/write access for typed/untyped files also depends on FileMode

10

expect opening failures:

  • handle I/O status explicitly with {$I-} and IOResult when useful
  • report errors in terms meaningful to the user

11

read/write with a file variable first:

  • read(f, x), write(f, x)
  • text interface converts to/from textual representation
  • typed-file interface transfers a fixed-size value representation
  • readln/writeln apply to text; eof(f) tests a specified stream

12

untyped files use BlockRead / BlockWrite

13

close(f) ends work with the open stream:

  • afterward f may be reopened for the same path or assigned a different one

14

HelloFile example:

  • assign, rewrite, writeln(f, message), close
  • Unix output contains greeting plus newline
  • check opening, writing, and final close/flush failures when correctness matters
  • successful open does not guarantee successful later writes

15

current position:

  • ordinary reading/writing advances it by transferred data
  • successive reads obtain successive portions
  • some file interfaces allow explicit repositioning
Book example (1 file) - 2.9.1: General principles
Book exampleBook example: hellofile.pasIn catalog
hellofile.pasPascal / 12 lines
program HelloFile;
const
    message = 'Hello, world!';
    filename = 'hello.txt';
var
    f: text;
begin
    assign(f, filename);
    rewrite(f);
    writeln(f, message);
    close(f)
end.

Text Files

Text files are line-oriented and human-readable:

var
    f: text;
    s: string;
begin
    assign(f, 'input.txt');
    reset(f);
    while not eof(f) do begin
        readln(f, s);
        writeln(s);
    end;
    close(f);
end.

input and output are predefined text files for standard input and standard output.

Detailed notes - 2.9.2: Text files

1

text file:

  • data represented as characters, usually organized into lines
  • same broad representation used by standard textual streams

2

text file variables support line operations:

  • readln, writeln, eoln
  • these operations have no equivalent line meaning in arbitrary binary records

3

numeric text I/O converts representations:

  • output: machine value -> digit characters
  • input: digit characters -> machine value

4

number-file example:

  • write 100 values starting at 1000, incrementing by 1001
  • text version uses writeln(f, n), one numeral per line
  • Pascal's text interface is sequential
  • reset opens for reading; rewrite/append for writing
  • editing variable-length content commonly means writing a replacement file

5

numeric EOF/EOL tests:

  • SeekEof(f) skips whitespace before checking whether meaningful input remains
  • SeekEoln(f) checks whether the current line has another nonspace token

6

sum of line products:

  • get filename from argument; open and check success
  • sum := 0
  • for each nonempty group: mul := 1; read/multiply numbers until end of line
  • consume the line boundary with readln(f), then sum := sum+mul
  • 2*3*5 + 0.5*12 = 36
  • malformed-number and read-error checks are needed beyond the simplified example

7

SeekEof / SeekEoln depend on text conventions:

  • whitespace and line boundaries are not generic binary-record separators

8

standard streams have file-variable names:

  • input and output are text variables
  • writeln(output, 'Hello') is explicit standard output
  • a var text parameter can accept an opened text file or output

9

additional Free Pascal names:

  • stdin / stdout
  • ErrOutput / stderr for diagnostics
Book examples (2 files) - 2.9.2: Text files
Book exampleBook example: gennumtx.pasIn catalog
gennumtx.pasPascal / 21 lines
program GenerateNumTxt;
const
    name = 'numbers.txt';
    start = 1000;
    step = 1001;
    count = 100;
var
    f: text;
    i: integer;
    n: longint;
begin
    assign(f, name);
    rewrite(f);
    n := start;
    for i := 1 to count do
    begin
        writeln(f, n);
        n := n + step
    end;
    close(f)
end.
Book exampleBook example: multandadd.pasIn catalog
multandadd.pasPascal / 33 lines
program MultAndAdd;
var
    sum, mul, n: real;
    f: text;
begin
    {$I-}
    if ParamCount < 1 then
    begin
        writeln('Please specify the file name');
        halt
    end;
    assign(f, ParamStr(1));
    reset(f);
    if IOResult <> 0 then
    begin
        writeln('Could not open ', ParamStr(1));
        halt
    end;
    sum := 0;
    while not SeekEof(f) do
    begin
        mul := 1;
        while not SeekEoln(f) do
        begin
            read(f, n);
            mul := mul * n
        end;
        readln(f);
        sum := sum + mul
    end;
    close(f);
    writeln(sum:7:5)
end.

Typed Files

A typed file stores values of one Pascal type:

type
    Item = record
        key: longint;
        value: longint;
    end;
var
    f: file of Item;

Typed files are compact and easy for Pascal programs to read, but they are not good interchange formats unless the exact layout is controlled.

Detailed notes - 2.9.3: Typed files

1

typed file = sequence of fixed-size representations:

  • file of longint stores longint values directly
  • same generating loop as text example, but write replaces writeln
  • representation depends on type/compiler/platform; it is not a portable text encoding

2

element-type restrictions:

  • file variables cannot be stored as file elements
  • pointer values generally have no useful persistent meaning in another execution
  • file of char can access a byte-oriented file one element at a time

3

record elements:

  • NamedPoint combines coordinates and a bounded name
  • file of NamedPoint stores a sequence of those records
  • rewrite creates/truncates; reset opens existing data

4

seek(f, index) selects a zero-based record position:

  • fixed size makes direct positioning possible
  • to change record 705: seek, read, alter field, seek back, write
  • second seek is necessary because read advanced to record 706

5

positioning requires a seekable stream:

  • regular files support it
  • terminal/pipe streams do not provide ordinary random-access file semantics

6

default typed-file access in the described runtime:

  • reset normally requests reading and writing
  • rewrite creates/truncates, while reset preserves existing contents

7

FileMode controls reset's access mode:

  • 0: read only; 1: write only; 2: read/write
  • select read-only mode when only reading is needed
  • write-only reset still preserves previous contents
  • FileMode does not give rewrite the same mode behavior
Book example (1 file) - 2.9.3: Typed files
Book exampleBook example: gennumbin.pasIn catalog
gennumbin.pasPascal / 21 lines
program GenerateNumBin;
const
    name = 'numbers.bin';
    start = 1000;
    step = 1001;
    count = 100;
var
    f: file of longint;
    i: integer;
    n: longint;
begin
    assign(f, name);
    rewrite(f);
    n := start;
    for i := 1 to count do
    begin
        write(f, n);
        n := n + step
    end;
    close(f)
end.

Untyped Files and Block I/O

Untyped files are used for byte/block operations:

var
    f: file;

Use blockread and blockwrite when the program needs raw binary transfer.

Detailed notes - 2.9.4: Block I/O

1

untyped files transfer arbitrary chunks:

  • practical interface close to operating-system byte/block I/O

2

transfer data between file and memory buffer:

  • opening specifies block size
  • each transfer specifies a number of blocks
  • block size 1 makes those counts byte counts

3

declare f: file:

  • assign as usual
  • reset(f, 1) or rewrite(f, 1) explicitly chooses one-byte blocks
  • omitted block size defaults to 128 in the discussed interface

4

opening modes:

  • FileMode affects reset as with typed files

5

BlockRead / BlockWrite arguments:

  • file variable
  • buffer variable
  • requested block count
  • variable receiving actual transferred count
  • block_count * block_size must fit the buffer
  • short read may simply mean fewer bytes remain
  • zero bytes read without an I/O error indicates EOF

6

keep the actual-count result:

  • omitting it can turn ordinary short reads into runtime errors
  • check I/O status as well when an actual error must be distinguished from EOF

7

copy-file example:

  • source/destination paths come from arguments
  • source opened read-only; destination created/truncated
  • transfer buffer = 4096 bytes; block size = one byte

8

copy loop:

  • read a chunk and inspect actual count/status
  • stop at EOF before attempting a write
  • write exactly the bytes read, including a partial final chunk
  • compare actual written count with actual read count
  • close both files; send diagnostics to ErrOutput
  • sample's write-error branch only breaks; a complete version must also return failure
  • read and final close errors also require checks for reliable copying
Book example (1 file) - 2.9.4: Block I/O
Book exampleBook example: block_cp.pasIn catalog
block_cp.pasPascal / 44 lines
program BlockFileCopy;
const
    BufSize = 4096;
var
    src, dest: file;
    buffer: array [1..BufSize] of byte;
    ReadRes, WriteRes: longint;
begin
    {$I-}
    if ParamCount < 2 then
    begin
        writeln(ErrOutput, 'Expected: source and dest. names');
        halt(1)
    end;
    assign(src, ParamStr(1));
    assign(dest, ParamStr(2));
    filemode := 0;
    reset(src, 1);            { block size of 1 byte }
    if IOResult <> 0 then
    begin
        writeln(ErrOutput, 'Couldn''t open ', ParamStr(1));
        halt(1)
    end;
    rewrite(dest, 1);
    if IOResult <> 0 then
    begin
        writeln(ErrOutput, 'Couldn''t open ', ParamStr(2));
        halt(1)
    end;
    while true do
    begin
        BlockRead(src, buffer, BufSize, ReadRes);
        if ReadRes = 0 then    { end of file! }
            break;
        BlockWrite(dest, buffer, ReadRes, WriteRes);
        if WriteRes <> ReadRes then
        begin
            writeln(ErrOutput, 'Error writing the file');
            break
        end
    end;
    close(src);
    close(dest)
end.

File Operations

Free Pascal provides operations on whole files:

Procedure Meaning
erase(f) Delete file assigned to f
rename(f, newname) Rename file assigned to f

Always check errors in serious programs. Silent file failures are hard to debug.

Detailed notes - 2.9.5: Operations on whole files

1

whole-file operations:

  • erase deletes a file
  • rename changes its filesystem name

2

use an assigned, closed file variable:

  • assign(f, path) before erase(f)
  • assign(f, old_path) before rename(f, new_path)
  • any of the file-variable categories can be used
  • if it was open, close it first
  • examples validate command-line arguments and check IOResult
  • report failure through ErrOutput and a nonzero exit status
Book example (1 file) - 2.9.5: Operations on whole files
Book exampleBook example: erase_f.pasIn catalog
erase_f.pasPascal / 18 lines
program EraseFile;
var
    f: file;
begin
    {$I-}
    if ParamCount < 1 then
    begin
        writeln(ErrOutput, 'Please specify the file to erase');
        halt(1)
    end;
    assign(f, ParamStr(1));
    erase(f);
    if IOResult <> 0 then
    begin
        writeln(ErrOutput, 'Error erasing the file');
        halt(1)
    end
end.

Addresses, Pointers, and Dynamic Memory

Detailed notes - 2.10: Addresses, pointers, and dynamic memory

1

variables declared in the program:

  • their types and sizes determine memory requirements before execution

2

memory requirements may depend on the input:

  • fixed teaching limits do not necessarily suit real tasks
  • sort accepts arbitrary line lengths and counts, within available resources
  • allocate the memory needed by the particular input

3

dynamic variables:

  • created during execution; accessed through addresses and pointers
  • let the program determine its memory needs at runtime
  • pointers also have uses beyond dynamic allocation

4

pointers may take considerable effort to understand

5

preparation for C:

  • Pascal permits substantial programming before introducing pointers
  • C requires a clear understanding of addresses from an early stage

6

do not leave pointers unresolved before proceeding:

  • seek help, practise with familiar tools, or study the assembly material
  • return after gaining experience if necessary

Pointers

A pointer stores an address. nil means "points nowhere".

Typed pointer:

type
    PInteger = ^integer;
var
    p: PInteger;

p^ means the object pointed to by p.

Detailed notes - 2.10.1: What a pointer is

1

address:

  • information uniquely identifying a memory cell
  • often an integer; some architectures use more complex representations

2

memory region:

  • consecutive cells; a variable occupies such a region
  • address of the region = address of its first cell

3

pointer:

  • a variable containing an address
  • one region of memory can contain the address of another

4

A points to B = A contains B's address

  • pointer: variable; address: value stored in it
  • informal expressions such as 'return a pointer' usually mean return an address
Detailed notes - 2.10.2: Pointers in Pascal

1

typed pointers:

  • pointed-to type tells the compiler how to interpret the addressed region
  • p: ^integer; q: ^real
  • ^ replaces the upward arrow used in Wirth's original notation

2

address-of operation: @x

  • p := @r makes p contain r's address
  • applies to any variable, including array elements and record fields

3

original Pascal lacked address-of:

  • pointer use was largely restricted to dynamic variables
  • the dialect used here supplies @

4

dereference: p^

  • denotes the variable at the address contained in p
  • after p := @r, p^ and r denote the same variable
  • p^ := 25.7 changes r; writeln(p^) prints its value

5

untyped pointer: pointer

  • can hold an address without specifying the stored value's type
  • assignments to typed pointers can bypass useful type checks
  • interpreting a string's address as ^integer does not make an integer exist there

6

@ produces an untyped address by default in the dialect discussed

  • {$T+} enables typed addresses

7

nil:

  • special invalid address; indicates that a pointer currently points nowhere
  • often called a null pointer, although nil itself is a value

8

pointer notation:

  • ^t: pointer-to-t type
  • @x: address of x
  • p^: variable reached through p
  • nil: no addressed variable

Dynamic Variables

Dynamic variables are created on the heap:

new(p);
p^ := 42;
writeln(p^);
dispose(p);
p := nil;

Pascal does not normally provide garbage collection. Every successful new must eventually be matched by dispose when the object is no longer needed.

Detailed notes - 2.10.3: Dynamic variables

1

dynamic variable:

  • memory region created during execution
  • has no identifier of its own; accessed through an address

2

heap:

  • supplies storage for dynamic variables
  • disposing of a variable makes its region available for reuse
  • the allocation model described retains acquired heap memory until exit
  • freeing obsolete storage before allocating replacements can reduce peak use

3

new(p):

  • requires a typed pointer
  • allocates enough storage for the pointed-to type
  • stores the new region's address in p

4

p: ^string; new(p)

  • creates a string variable in the heap
  • the short-string representation used here occupies 256 bytes
  • p^ := 'This is a string, which resides in the heap' fills it

5

dispose(p):

  • releases the variable addressed by p
  • does not change p itself
  • p still contains the old address, which must no longer be dereferenced

6

allocation belongs to an address, not to one particular pointer:

  • q := p copies the address; p^ and q^ denote the same variable
  • p can subsequently be reused while q retains access
  • dispose(q) releases that same allocation

7

losing the only address:

  • a second new(p) overwrites p without disposing of its previous allocation
  • the first variable remains allocated but can no longer be reached

8

garbage:

  • unreachable allocated memory
  • distinct from junk: meaningless/uninitialized data
  • some languages reclaim garbage automatically; collection can pause execution

9

memory leak:

  • allocated storage is lost without being released
  • this Pascal model has no automatic garbage collection
  • retain ownership information and dispose of unneeded variables

10

why use dynamic storage:

  • large temporary objects can exceed practical stack limits
  • allocate and release objects according to when they are needed
  • the main applications here are linked structures built from records containing pointers

Linked Lists

A node usually contains data and a pointer to the next node:

type
    PNode = ^Node;
    Node = record
        value: integer;
        next: PNode;
    end;

The type PNode is declared before Node is fully known. Pascal allows this special forward reference for pointer types, which is essential for recursive data structures.

Basic list operations:

Sorted insertion needs no special case for the head of the list. p is a variable parameter, so push can change either the head pointer or the next field of the previous node:

procedure insert(var p: itemptr; n: integer);
begin
    if (p = nil) or (n < p^.data) then
        push(p, n)
    else
        insert(p^.next, n)
end;
Show the complete program
program list;
type
    itemptr = ^item;
    item = record
    data: integer;
    next: itemptr;
    end;

procedure init(var p: itemptr);
begin
    p := nil;
end;

procedure print(p: itemptr);    { a copy: the caller keeps its list }
begin
    while (p <> nil) do
    begin
        write(p^.data, ' ');
        p := p^.next
    end;
    writeln()
end;

procedure push(var p: itemptr; n: integer);
var
    tmp: itemptr;
begin
    new(tmp);
    tmp^.data := n;
    tmp^.next := p;
    p := tmp;
end;

procedure insert(var p: itemptr; n: integer);
begin
    if (p = nil) or (n < p^.data) then
        push(p, n)
    else
        insert(p^.next, n)
end;

var
    i: integer;
    a: array [1..4] of integer = (1, 3, 6, 9);
    p: itemptr;
begin
    init(p);
    for i := 4 downto 1 do
        push(p, a[i]);
    insert(p, 4);
    print(p);
end.
1 3 4 6 9
Detailed notes - 2.10.4: Singly linked lists

1

singly linked list:

  • each node contains data and a pointer to the next node
  • last node's next = nil
  • a pointer to the first node makes the whole chain reachable

2

one chain of links:

  • one next field per node
  • each node is reached through the preceding link or the head pointer

3

node type for integer data:

  • data: integer; next: pointer to the same record type
  • naming the record inside its own declaration is restricted in older Pascal implementations

4

forward pointer type:

  • declare itemptr = ^item before declaring item
  • item contains data: integer and next: itemptr
  • first^ = first record; first^.next = pointer to the second
  • first^.next^ = second record; first^.next^.data = its value
  • explicit new calls can build 25 -> 36 -> 49 -> nil

5

understand each dereference and field selection before continuing

6

usual construction methods:

  • prepend through a temporary pointer
  • or maintain first and last, and append
  • try implementing the exercises before reading the solutions

7

exercises:

  • read integers to EOF and print them in reverse order
  • read integers to EOF and print them twice in their original order
  • no fixed limit on the number of integers
  • a working, tested program is required; an imagined solution is insufficient

8

initialize an empty list: first := nil

  • an uninitialized pointer does not represent a valid empty list

9

prepend in three stages:

  • allocate a node through tmp
  • set its data and make tmp^.next point to the old first node
  • assign first := tmp

10

prepending 25 to 36 -> 49:

  • new(tmp)
  • tmp^.data := 25; tmp^.next := first
  • first := tmp
  • allocation alone leaves the original list unchanged and the new fields uninitialized

11

empty-list case needs no separate prepend algorithm:

  • the old first is nil, so the new node's next becomes nil
  • requires correct initial first := nil

12

reverse-order program:

  • read with while not SeekEof; prepend each value
  • traverse from first while tmp <> nil; print tmp^.data; advance tmp := tmp^.next

list disposal:

  • save first^.next, dispose(first), then replace first with the saved address
  • or save first, advance first, then dispose the saved node
  • never read a node's next after disposing of that node
  • exit releases the example's storage; repeated work in a longer program needs explicit disposal

13

preserve input order by appending:

  • reversing an already built list is possible, but unnecessary here

14

append with first and last:

  • empty list: both nil; allocate first and assign last := first
  • nonempty list: new(last^.next); last := last^.next
  • fill last^.data and set last^.next := nil

alternative using tmp:

  • allocate and fill tmp, with tmp^.next := nil
  • if empty, first := tmp; otherwise last^.next := tmp
  • finish with last := tmp
  • draw and check both the empty and nonempty cases

15

complete the second exercise independently:

  • append during input, then traverse the completed list twice
Allocate and initialize a new node, link it to the old head, then replace the head pointer.
Prepend without losing the old list. Open full size - Editable SVG
Examples & tests (3 files) - 2.10.4: Singly linked lists
Book exampleBook example: qol.pasIn catalog
qol.pasPascal / 67 lines
program QOLDemo;
type
    LongItemPtr = ^LongItem;
    LongItem = record
        data: longint;
        next: LongItemPtr;
    end;
type
    QueueOfLongints = record
        first, last: LongItemPtr;
    end;

procedure QOLInit(var queue: QueueOfLongints);
begin
    queue.first := nil;
    queue.last := nil
end;

procedure QOLPut(var queue: QueueOfLongints; n: longint);
begin
    if queue.first = nil then
    begin
        new(queue.first);
        queue.last := queue.first
    end
    else
    begin
        new(queue.last^.next);
        queue.last := queue.last^.next
    end;
    queue.last^.data := n;
    queue.last^.next := nil
end;

procedure QOLGet(var queue: QueueOfLongints; var n: longint);
var
    tmp: LongItemPtr;
begin
    n := queue.first^.data;
    tmp := queue.first;
    queue.first := queue.first^.next;
    if queue.first = nil then
        queue.last := nil;
    dispose(tmp)
end;

function QOLIsEmpty(var queue: QueueOfLongints) : boolean;
begin
    QOLIsEmpty := queue.first = nil
end;

var
    s: QueueOfLongints;
    n: longint;
begin
    QOLInit(s);
    while not eof do
    begin
        readln(n);
        QOLPut(s, n)
    end;
    while not QOLIsEmpty(s) do
    begin
        QOLGet(s, n);
        writeln(n)
    end
end.
Book exampleBook example: sol.pasIn catalog
sol.pasPascal / 56 lines
program SOLDemo;
type
    LongItemPtr = ^LongItem;
    LongItem = record
        data: longint;
        next: LongItemPtr;
    end;
type
    StackOfLongints = LongItemPtr;

procedure SOLInit(var stack: StackOfLongints);
begin
    stack := nil
end;

procedure SOLPush(var stack: StackOfLongints; n: longint);
var
    tmp: LongItemPtr;
begin
    new(tmp);
    tmp^.data := n;
    tmp^.next := stack;
    stack := tmp
end;

procedure SOLPop(var stack: StackOfLongints; var n: longint);
var
    tmp: LongItemPtr;
begin
    n := stack^.data;
    tmp := stack;
    stack := stack^.next;
    dispose(tmp)
end;

function SOLIsEmpty(var stack: StackOfLongints) : boolean;
begin
    SOLIsEmpty := stack = nil
end;

var
    s: StackOfLongints;
    n: longint;
begin
    SOLInit(s);
    while not eof do
    begin
        readln(n);
        SOLPush(s, n)
    end;
    while not SOLIsEmpty(s) do
    begin
        SOLPop(s, n);
        writeln(n)
    end
end.
Section test04 (02-10)In catalog
list.pasPascal / 52 lines
program list;
type
    itemptr = ^item;
    item = record
    data: integer;
    next: itemptr;
    end;

procedure init(var p: itemptr);
begin
    p := nil;
end;

procedure print(var p: itemptr);
begin
    while (p <> nil) do
    begin
        write(p^.data, ' ');
        p := p^.next
    end;
    writeln()
end;

procedure push(var p: itemptr; n: integer);
var
    tmp: itemptr;
begin
    new(tmp);
    tmp^.data := n;
    tmp^.next := p;
    p := tmp;
end;

procedure insert(var p: itemptr; n: integer);
begin
    if (p = nil) or (n < p^.data) then
        push(p, n)
    else
        insert(p^.next, n)
end;

var
    i: integer;
    a: array [1..4] of integer = (1, 3, 6, 9);
    p: itemptr;
begin
    init(p);
    for i := 4 downto 1 do
        push(p, a[i]);
    insert(p, 4);
    print(p);
end.

Stack and Queue

A stack is LIFO: last in, first out. With a linked list, push and pop are operations at the head.

A queue is FIFO: first in, first out. It usually keeps both head and tail pointers.

Etude 2.42 prints the words of each input line in reverse order, without the string type and without limits on lengths. Each word is a queue of characters, appended at its tail; the words of a line form a stack, so they come out reversed:

type
    pwt = ^wt;
    wt = record
        c: char;
        n: pwt
    end;
    pwts = record
        b: pwt;
        e: pwt
    end;
    pst = ^st;
    st = record
        w: pwts;
        n: pst;
    end;
procedure AppendStr(w: pwts; var s: pst);
var
    t: pst;
begin
    new(t);
    t^.w := w;
    t^.n := s;
    s := t;
end;
Show the complete program
program ptrnum;
type
    pwt = ^wt;
    wt = record
        c: char;
        n: pwt
    end;
    pwts = record
        b: pwt;
        e: pwt
    end;
    pst = ^st;
    st = record
        w: pwts;
        n: pst;
    end;

procedure InitWord(var w: pwts);
begin
    w.b := nil;
    w.e := nil
end;

procedure InitStr(var s: pst);
begin
    s := nil
end;

procedure AppendChar(c: char; var w: pwts);
var
    t: pwt;
begin
    new(t);
    t^.c := c;
    t^.n := nil;
    if (w.b = nil) then
    begin
        w.b := t;
        w.e := w.b
    end
    else
    begin
        w.e^.n := t;
        w.e := w.e^.n
    end
end;

procedure AppendStr(w: pwts; var s: pst);
var
    t: pst;
begin
    new(t);
    t^.w := w;
    t^.n := s;
    s := t;
end;

procedure ReadWord(var w: pwts; var next: boolean);
var
    c: char;
begin
    while true do
    begin
        read(c);
        if (c = ' ') or (c = #9) then
            exit
        else if (c = #10) then
        begin
            next := true;
            exit
        end;
        AppendChar(c, w)
    end
end;

procedure ReadStr(var s: pst);
var
    w: pwts;
    next: boolean;
begin
    InitStr(s);
    next := false;
    while not next do
    begin
        InitWord(w);
        ReadWord(w, next);
        AppendStr(w, s);
    end
end;

procedure WriteWord(var w: pwts);
var
    t, t1: pwt;
begin
    t := w.b;
    while (t <> nil) do
    begin
        write(t^.c);
        t1 := t;
        t := t^.n;
        dispose(t1)
    end;
    write(' ');
end;

procedure WriteStr(var s: pst);
var
    t, t1: pst;
begin
    t := s;
    while (t <> nil) do
    begin
        WriteWord(t^.w);
        t1 := t;
        t := t^.n;
        dispose(t1)
    end;
    writeln()
end;

var
    s: pst;
begin
    while not SeekEof do
    begin
        ReadStr(s);
        WriteStr(s)
    end
end.
wall a on sat Dumpty Humpty
Detailed notes - 2.10.5: Stack and queue

1

stack and queue describe behavior:

  • can be implemented using lists, arrays, circular buffers, or external storage
  • their identity is determined by operations and retrieval order

2

both store values and support insertion/extraction:

  • queue = FIFO: first in, first out
  • stack = LIFO: last in, first out

3

queue returns the oldest remaining value

stack returns the newest remaining value

4

singly linked implementations:

  • stack: insert and remove at the beginning
  • queue: append at the end; remove at the beginning

5

hide implementation behind subprograms:

  • clients use operations without depending on the representation
  • changing list storage to array storage should affect those subprograms alone

6

interface:

  • available procedures/functions plus the rules for using them
  • a good interface remains usable when implementation details change

7

design interface first:

  • start with the operations the user needs
  • choose a representation afterward

8

StackOfLongints:

  • one variable represents each independent stack
  • its eventual type can be a record or another suitable representation
  • give the type a name before committing to its contents

9

stack operations:

  • SOLPush(var stack; n): insert a longint
  • SOLPop(var stack; var n): remove the top value and return it through n
  • both receive the stack by reference because they change it

10

SOLIsEmpty(var stack): boolean

  • check before popping unless nonemptiness is already certain
  • by-reference parameter also avoids copying a potentially large representation
  • the contract excludes popping an empty stack

11

SOLInit makes a newly declared variable a valid empty stack

implementation:

  • StackOfLongints = pointer to the first LongItem
  • init: nil; push: prepend; pop: extract data, unlink first, dispose it
  • empty: stack = nil
  • reverse-input example pushes all numbers, then pops and prints until empty

12

alternative boolean SOLPop:

  • returns false for an empty stack; otherwise extracts n and returns true
  • permits while SOLPop(s, n) do writeln(n)
  • combines a result with a side effect; the book postpones this style

13

QueueOfLongints interface:

  • QOLInit, QOLPut, QOLGet, QOLIsEmpty
  • represent a queue with a record containing first and last
  • init sets both nil; put appends, handling the initially empty queue
  • get copies first^.data, advances first, and disposes the old node
  • when removal empties the queue, also set last := nil
  • check emptiness through first = nil; never get from an empty queue
Stack operations use one end; queue insertion and removal use opposite ends.
One arrival sequence, two removal orders. Open full size - Editable SVG

Pointer to Pointer Traversal

Deletion in a linked list becomes simpler when the program keeps a pointer to the link that leads to the current node. The idea is to modify the place where the current node is referenced, not only the current node itself.

This technique is important in C; Pascal lets us learn the structure before C makes pointer syntax unavoidable.

Detailed notes - 2.10.6: Traversing a list with a pointer to a pointer

1

remove every negative value:

  • removing the first node changes first
  • removing another node changes its predecessor's next

2

ordinary traversal loses the predecessor:

  • a predecessor-based loop needs separate handling for negative head nodes
  • an additional prev pointer reduces duplication but still needs a head special case

3

pointer to the incoming link: pp: ^itemptr

  • can contain @first or the address of any node's next field
  • pp^ = pointer to the current node; pp^^ = current node
  • start pp := @first
  • advance pp := @(pp^^.next)

4

advance only when keeping the current node:

  • after removal, the same incoming link already points to the next candidate

5

traverse while pp^ <> nil

removal:

  • tmp := pp^; pp^ := pp^^.next; dispose(tmp)
  • otherwise advance pp to the current node's next field
  • identical handling for first, interior, and consecutive removed nodes
  • empty lists need no separate branch

6

insertion at the link held by pp:

  • new(tmp); tmp^.next := pp^; tmp^.data := n; pp^ := tmp
  • works before any node and at the end where pp^ = nil
  • every list tail is itself a list, with its incoming link acting as a head pointer

7

sorted list:

  • locate the insertion position that preserves the ordering

8

ascending insertion:

  • begin at @first; advance while a next candidate exists and its value is smaller than n
  • insert before the first value >= n, or at the end

9

stop comparison:

  • pp^^.data >= n means the correct position has been found

10

nil protection:

  • pp^^.data is invalid when pp^ = nil
  • separate checks prevent dereferencing a nonexistent node

11

short-circuit evaluation:

  • while (pp^ <> nil) and (pp^^.data < n) do ...
  • if the first operand is false, the second need not be evaluated
  • permits the compact condition without dereferencing nil

12

dialect differences:

  • original Pascal evaluated all boolean operands and lacked break and @
  • neither the compact guarded condition nor this pointer-to-pointer technique transfers unchanged to it

13

Free Pascal evaluation directives:

  • {$B+}: full boolean evaluation; {$B-}: short-circuit evaluation
  • the examples depend on short-circuit evaluation where conditions guard dereferences

14

dummy head alternative:

  • an extra node can supply an incoming next field for the first real node
  • the pointer-to-pointer method handles first directly, without that extra node

Doubly Linked Lists and Deques

A doubly linked node has next and prev links. It supports movement in both directions and efficient deletion when the node pointer is already known.

A deque is a double-ended queue: insert and remove at both front and back.

Detailed notes - 2.10.7: Doubly linked lists; deques

1

doubly linked lists extend the one-way list structure

2

each node contains two links:

  • prev points to the predecessor; next points to the successor
  • forward and backward chains connect the same nodes
  • first and last commonly identify the two ends

3

item2 record:

  • data: integer; prev, next: item2ptr
  • use conventional prev and next names to make the roles clear

4

cost and benefit:

  • extra pointer storage and more link updates on insertion/removal
  • traversal can proceed in either direction

5

any node gives access to the whole chain:

  • its prev finds the predecessor and hence the incoming next link
  • at the beginning update first; at the end update last
  • both neighboring links must agree after insertion/removal

6

insert beside current:

  • left: tmp.prev := current.prev; tmp.next := current
  • reconnect predecessor.next or first to tmp; set current.prev := tmp
  • right: symmetric changes to next, successor.prev, and last

remove current:

  • reconnect predecessor.next or first to current.next
  • reconnect successor.prev or last to current.prev
  • dispose current only after saving the address needed for continuing traversal

7

insert at the ends:

  • prepend: tmp.prev := nil; tmp.next := first
  • update old first.prev, or last if empty; then first := tmp
  • append is symmetric

generalized insertion:

  • insertion before current = nil can mean append
  • insertion after current = nil can mean prepend
  • initialize both new links, then update each neighbor or corresponding end pointer

8

deque:

  • insert and extract at either end
  • extracting at the insertion end gives the newest value first
  • extracting at the opposite end gives the oldest value first

9

operation names:

  • pushfront, pushback, popfront, popback
  • selected pairs provide stack or queue behavior
  • use simpler stack/queue implementations when only those operations are needed

10

LongDeque exercise:

  • record containing first and last pointers to doubly linked nodes
  • implement Init, PushFront, PushBack, PopFront, PopBack, IsEmpty
  • require a nonempty deque before either extraction

Other Dynamic Structures

The same pointer ideas lead to:

The implementation changes, but the memory discipline remains the same: know who owns each allocated object and when it is freed.

Detailed notes - 2.10.8: Other dynamic data structures

1

search key:

  • data used to find a record, such as inventory number, name, or address
  • record also contains the associated information returned by the search

2

linear list search:

  • follow links one by one until finding the key
  • work grows proportionally to the number of records
  • a sorted list still lacks direct access to its middle

3

scaling:

  • repeated linear searches become increasingly expensive as the collection grows

4

binary search tree:

  • nodes contain left and right child pointers
  • nil child pointer = empty subtree

5

search-tree invariant:

  • smaller keys belong in the left subtree; larger keys in the right
  • applies recursively at every node
  • searching follows one branch per comparison; work depends on height
  • height h can accommodate up to 2^h - 1 nodes
  • a densely filled tree of height 20 holds over a million nodes

6

unbalanced tree:

  • can have substantial height despite few nodes
  • sorted insertion can produce a single chain, with linear search cost
  • balancing reduces height but needs additional algorithms

7

tree variations:

  • recursive code naturally expresses binary-tree operations
  • nodes may have more than two children
  • a character trie selects a child using the next character; height depends on key length

8

search costs:

  • list: proportional to record count
  • balanced binary tree: proportional to log2(record count)
  • hash tables aim at constant expected lookup cost under suitable loading/distribution

9

hash function and table:

  • same key always gives the same hash; different keys should spread well
  • bucket/index = hash(key) mod table size
  • the example uses a generously sized array, commonly with prime length

10

collision:

  • different keys select the same position
  • empty position means absent key in the basic lookup scheme
  • chaining stores a list of colliding records at each table position
  • lists add allocation, linking, and traversal overhead

11

linear probing:

  • continue through successive positions until finding the key or an empty slot
  • insert in the first available slot
  • deleting an entry must preserve reachability of later entries in its probe chain
  • one method removes and reinserts the following cluster up to its first empty slot

12

load factor and resizing:

  • crowded tables spend more time resolving collisions
  • the book suggests staying below roughly two-thirds occupancy
  • grow the array and reinsert every record using the new modulus
  • resizing requires substantial work; old positions cannot simply be retained

13

dynamically sized arrays:

  • needed when the table capacity is chosen or changed during execution
  • available in modern Pascal dialects, beyond the subset covered here

More Recursion

Detailed notes - 2.11: More about recursion

1

strings, lists, and trees provide more substantial uses of recursion

  • revisit the technique with a larger set of programming tools

Mutual Recursion

Two subprograms may call each other. Pascal needs a forward declaration when a name is used before its full body:

function IsOdd(n: integer): boolean; forward;

function IsEven(n: integer): boolean;
begin
    if n = 0 then
        IsEven := true
    else
        IsEven := IsOdd(n - 1);
end;

function IsOdd(n: integer): boolean;
begin
    if n = 0 then
        IsOdd := false
    else
        IsOdd := IsEven(n - 1);
end;
Detailed notes - 2.11.1: Mutual recursion

1

mutual recursion:

  • one subprogram calls another, which calls the first
  • the earlier definition needs information about the later subprogram

2

forward declaration:

  • header followed by forward; gives the name, parameters, and result type
  • contains no local declarations or body
  • lets the compiler check calls and generate argument conversions before seeing the implementation

3

declaration order:

  • declare the first subprogram forward
  • define the second, then provide the first subprogram's complete definition
  • both bodies can then refer to both names

4

every forward declaration requires a later matching definition

Towers of Hanoi

The recursive structure is:

  1. move n - 1 disks from source to spare
  2. move the largest disk from source to destination
  3. move n - 1 disks from spare to destination

The number of moves is 2^n - 1.

Detailed notes - 2.11.2: Towers of Hanoi

1

implement the recursive algorithm introduced with the idea of an algorithm

2

task:

  • three rods; N differently sized disks initially stacked largest to smallest
  • move one disk at a time; never place a larger disk on a smaller one
  • transfer the whole stack using the fewest moves

3

recursive decomposition:

  • move n-1 disks from source to transit
  • move disk n from source to target
  • move n-1 disks from transit to target
  • base case n = 0: nothing to do

4

solve(source, target, transit, n):

  • recursive calls exchange rod roles as required
  • output identifies the disk and its source/target rods
  • validate the command-line disk count with val and require n >= 1
  • start solve(1, 3, 2, n)

5

alternative iterative algorithm:

  • odd moves: move the smallest disk around the rods
  • even disk count: 1 -> 2 -> 3 -> 1; odd count: reverse direction
  • even moves: perform the sole legal move excluding the smallest disk

6

apparently simple physical actions need explicit program state:

  • track which disks occupy each rod
  • compare top disks and handle empty rods

7

hanoi2 representation:

  • three singly linked lists, one per rod; array of head pointers
  • continue until rods 1 and 2 are empty
  • compute smallest-disk moves from the turn number
  • other moves find its rod, exclude it, then choose the legal direction between the remaining rods

8

iterative implementation is much longer:

  • bookkeeping dominates the concise recursive description

9

recursion can also be replaced by an explicit task stack:

  • preserve the original recursive decomposition
  • a loop processes stored unfinished tasks

10

task record:

  • disk count, source rod, target rod, state, and next pointer
  • StClearing: prepare to move the smaller disks away
  • StLargest: move the largest disk, then bring the smaller disks onto it
  • StFinal: task complete; remove it

processing:

  • start with one task transferring all disks from 1 to 3
  • in StClearing, change the current task to StLargest
  • if more than one disk remains, push the task for clearing n-1 disks
  • tasks remember where suspended work must resume

11

StLargest:

  • print the move of disk amount from src to dst
  • change the current task to StFinal
  • if needed, push a task moving smaller disks from transit to target
  • when a StFinal task returns to the front, unlink and dispose it

12

IntermRod(src, dst):

  • returns the rod number different from both src and dst
  • supplies the intermediate rod for each newly created subtask

13

hanoi3:

  • explicit task management is shorter than the first iterative approach
  • still substantially more code than the recursive solution
Move the smaller tower away, move the largest disk, then move the smaller tower onto it.
Hanoi splits one task into three tasks. Open full size - Editable SVG
Book examples (3 files) - 2.11.2: Towers of Hanoi
Book exampleBook example: hanoi.pasIn catalog
hanoi.pasPascal / 27 lines
program hanoi;

procedure solve(source, target, interm, n: integer);
begin
    if n = 0 then
        exit;
    solve(source, interm, target, n-1);
    writeln(n, ': ',  source, ' -> ', target);
    solve(interm, target, source, n-1)
end;

var
    n, code: integer;
begin
    if ParamCount < 1 then
    begin
        writeln(ErrOutput, 'No parameters given');
        halt(1)
    end;
    val(ParamStr(1), n, code);
    if (code <> 0) or (n < 1) then
    begin
        writeln(ErrOutput, 'Invalid token count');
        halt(1)
    end;
    solve(1, 3, 2, n)
end.
Book exampleBook example: hanoi2.pasIn catalog
hanoi2.pasPascal / 111 lines
program hanoi2;

type
    pdisk = ^disk;
    disk = record
        k: integer;
        next: pdisk;
    end;
    RodsArray = array [1..3] of pdisk;

procedure MoveDiskItem(var RodFrom, RodTo: pdisk);
var
    tmp: pdisk;
begin
    tmp := RodFrom;
    RodFrom := RodFrom^.next;
    tmp^.next := RodTo;
    RodTo := tmp
end;

procedure MoveDisk(var rods: RodsArray; src, dst: integer);
begin
    writeln(rods[src]^.k, ': ', src, ' -> ', dst);
    MoveDiskItem(rods[src], rods[dst])
end;

procedure MoveSmallest(var rods: RodsArray; turn, total: integer);
var
    src, dst: integer;
begin
    if total mod 2 = 0 then
    begin
        src := (turn div 2) mod 3 + 1;
        dst := src + 1;
        if dst = 4 then
            dst := 1
    end
    else
    begin
        src := 3 - ((turn div 2 + 2) mod 3);
        dst := src - 1;
        if dst = 0 then
            dst := 3
    end;
    MoveDisk(rods, src, dst)
end;

procedure MoveLarger(var rods: RodsArray);
var
    src, dst, tmp: integer;
begin
    src := 1;
    dst := 2;
    if (rods[1] <> nil) and (rods[1]^.k = 1) then
        src := 3
    else
        if (rods[2] <> nil) and (rods[2]^.k = 1) then
            dst := 3;
    if (rods[src] = nil) or
        ((rods[dst] <> nil) and (rods[src]^.k > rods[dst]^.k)) then
    begin
        tmp := src;
        src := dst;
        dst := tmp
    end;
    MoveDisk(rods, src, dst)
end;

procedure solve(n: integer);
var
    rods: RodsArray;
    tmp: pdisk;
    i: integer;
    turn: integer;
begin
    for i := 1 to 3 do
        rods[i] := nil;
    for i := n downto 1 do
    begin
        new(tmp);
        tmp^.k := i;
        tmp^.next := rods[1];
        rods[1] := tmp
    end;
    turn := 1;
    while (rods[1] <> nil) or (rods[2] <> nil) do
    begin
        if turn mod 2 = 1 then
            MoveSmallest(rods, turn, n)
        else
            MoveLarger(rods);
        turn := turn + 1
    end
end;

var
    n, code: integer;
begin
    if ParamCount < 1 then
    begin
        writeln(ErrOutput, 'No parameters given');
        halt(1)
    end;
    val(ParamStr(1), n, code);
    if (code <> 0) or (n < 1) then
    begin
        writeln(ErrOutput, 'Invalid token count');
        halt(1)
    end;
    solve(n)
end.
Book exampleBook example: hanoi3.pasIn catalog
hanoi3.pasPascal / 90 lines
program hanoi3;

function IntermRod(src, dst: integer) : integer;
begin
    if (src <> 1) and (dst <> 1) then
        IntermRod := 1
    else
    if (src <> 2) and (dst <> 2) then
        IntermRod := 2
    else
        IntermRod := 3
end;

procedure solve(n: integer);
type
    TaskState = (StClearing, StLargest, StFinal);
    ptask = ^task;
    task = record
        amount, src, dst: integer;
        state: TaskState;
        next: ptask;
    end;
var
    first, tmp: ptask;
begin
    new(first);
    first^.amount := n;
    first^.src := 1;
    first^.dst := 3;
    first^.state := StClearing;
    first^.next := nil;
    while first <> nil do
    begin
        case first^.state of
            StClearing:
                begin
                    first^.state := StLargest;
                    if first^.amount > 1 then
                    begin
                        new(tmp);
                        tmp^.src := first^.src;
                        tmp^.dst := IntermRod(first^.src, first^.dst);
                        tmp^.amount := first^.amount - 1;
                        tmp^.state := StClearing;
                        tmp^.next := first;
                        first := tmp
                    end
                end;
            StLargest:
                begin
                    first^.state := StFinal;
                    writeln(first^.amount, ': ', first^.src,
                            ' -> ', first^.dst);
                    if first^.amount > 1 then
                    begin
                        new(tmp);
                        tmp^.src := IntermRod(first^.src, first^.dst);
                        tmp^.dst := first^.dst;
                        tmp^.amount := first^.amount - 1;
                        tmp^.state := StClearing;
                        tmp^.next := first;
                        first := tmp
                    end
                end;
            StFinal:
                begin
                    tmp := first;
                    first := first^.next;
                    dispose(tmp)
                end
        end
    end
end;

var
    n, code: integer;
begin
    if ParamCount < 1 then
    begin
        writeln(ErrOutput, 'No parameters given');
        halt(1)
    end;
    val(ParamStr(1), n, code);
    if (code <> 0) or (n < 1) then
    begin
        writeln(ErrOutput, 'Invalid token count');
        halt(1)
    end;
    solve(n)
end.

Pattern Matching

Recursive pattern matching splits a string problem into:

This is a useful example of recursion over text rather than numbers.

A matcher for ? (any one character) and * (any sequence). Ordinary characters advance in a loop; only * recurses, trying every possible length for the part it matches:

function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
    i: integer;
begin
    while true do
    begin
        if pi > length(pat) then
        begin
            MatchIdx := si > length(str);
            exit
        end;
        if pat[pi] = '*' then
        begin
            for i := 0 to (length(str) - si + 1) do
                if MatchIdx(str, pat, si+i, pi+1) then
                begin
                    MatchIdx := true;
                    exit
                end;
            MatchIdx := false;
            exit
        end;
        if (si > length(str)) or
           ((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
        begin
            MatchIdx := false;
            exit
        end;
        si := si + 1;
        pi := pi + 1
    end
end;
Show the complete program
program pattern;

function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
    i: integer;
begin
    while true do
    begin
        if pi > length(pat) then
        begin
            MatchIdx := si > length(str);
            exit
        end;
        if pat[pi] = '*' then
        begin
            for i := 0 to (length(str) - si + 1) do
                if MatchIdx(str, pat, si+i, pi+1) then
                begin
                    MatchIdx := true;
                    exit
                end;
            MatchIdx := false;
            exit
        end;
        if (si > length(str)) or
           ((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
        begin
            MatchIdx := false;
            exit
        end;
        si := si + 1;
        pi := pi + 1
    end
end;

function Match(str, pat: string): boolean;
begin
    Match := MatchIdx(str, pat, 1, 1);
end;


begin
    if ParamCount < 2 then
    begin
        writeln(ErrOutput, 'Two parameters expected');
        halt(1)
    end;
    if Match(ParamStr(1), ParamStr(2)) then
        writeln('yes')
    else
        writeln('no')
end.
yes
Detailed notes - 2.11.3: Pattern matching

1

match an entire string against a pattern:

  • ordinary character: matches itself
  • ?: matches one arbitrary character
  • *: matches any sequence, including an empty sequence
  • a?c matches abc; a* matches any string beginning with a

2

work with unprocessed suffixes:

  • previously removed prefixes have already matched
  • when the pattern ends, succeed only if the string has also ended

3

ordinary character or ?:

  • require an available string character
  • fail if an ordinary pattern character differs
  • otherwise advance both positions and continue

4

  • introduces alternatives:
  • try consuming zero, one, two, ... remaining string characters
  • recursively match the remaining pattern after the * against each resulting suffix
  • return true on the first success; false when all alternatives fail

5

MatchIdx(var str, pat; idxs, idxp): boolean

  • indexes identify suffixes without allocating shortened strings
  • pass strings by reference to avoid copies on every recursive call

6

Match(str, pat): boolean

  • public wrapper starts MatchIdx with both indexes equal to 1
  • value parameters accept literals and other string expressions
  • copy once at the interface, then recurse using references to those local copies

7

test program:

  • receive string and pattern as command-line arguments
  • print yes or no according to Match
  • quote arguments with apostrophes so the shell does not expand * or ?
  • abc / a?c -> yes; abc / a??c -> no; abc / ***a***c*** -> yes
Examples & tests (2 files) - 2.11.3: Pattern matching
Book exampleBook example: match_pt.pasIn catalog
match_pt.pasPascal / 51 lines
program MatchPattern;

function MatchIdx(var str, pat: string; idxs, idxp: integer): boolean;
var
    i: integer;
begin
    while true do
    begin
        if idxp > length(pat) then
        begin
            MatchIdx := idxs > length(str);
            exit
        end;
        if pat[idxp] = '*' then
        begin
            for i := 0 to length(str)-idxs+1 do
                if MatchIdx(str, pat, idxs+i, idxp+1) then
                begin
                    MatchIdx := true;
                    exit
                end;
            MatchIdx := false;
            exit
        end;
        if (idxs > length(str)) or
           ((str[idxs] <> pat[idxp]) and (pat[idxp] <> '?')) then
        begin
            MatchIdx := false;
            exit
        end;
        idxs := idxs + 1;
        idxp := idxp + 1;
    end
end;

function Match(str, pat: string): boolean;
begin
    Match := MatchIdx(str, pat, 1, 1)
end;

begin
    if ParamCount < 2 then
    begin
        writeln(ErrOutput, 'Two parameters expected');
        halt(1)
    end;
    if Match(ParamStr(1), ParamStr(2)) then
        writeln('yes')
    else
        writeln('no')
end.
Section test13 (02-11)In catalog
pattern.pasPascal / 52 lines
program pattern;

function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
    i: integer;
begin
    while true do
    begin
        if pi > length(pat) then
        begin
            MatchIdx := si > length(str);
            exit
        end;
        if pat[pi] = '*' then
        begin
            for i := 0 to (length(str) - si + 1) do
                if MatchIdx(str, pat, si+i, pi+1) then
                begin
                    MatchIdx := true;
                    exit
                end;
            MatchIdx := false;
            exit
        end;
        if (si > length(str)) or
           ((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
        begin
            MatchIdx := false;
            exit
        end;
        si := si + 1;
        pi := pi + 1
    end
end;

function Match(str, pat: string): boolean;
begin
    Match := MatchIdx(str, pat, 1, 1);
end;


begin
    if ParamCount < 2 then
    begin
        writeln(ErrOutput, 'Two parameters expected');
        halt(1)
    end;
    if Match(ParamStr(1), ParamStr(2)) then
        writeln('yes')
    else
        writeln('no')
end.

Recursion on Lists and Trees

For a list:

For a binary tree:

Binary search trees use ordering to guide insertion and search.

Detailed notes - 2.11.4: Recursion with lists

1

recursive list structure:

  • either empty, or a first node followed by another list

sum:

  • empty list -> 0
  • otherwise p^.data + ItemListSum(p^.next)
  • recursion uses stack space proportional to list length; deep lists can overflow it

2

dispose recursively:

  • empty list -> return
  • dispose the tail first, then dispose the current node
  • preserves access to next until the recursive call has used it

3

sorted insertion:

  • empty list or first value > n: prepend n
  • otherwise recursively insert into p^.next
  • receive p as a var parameter so insertion can replace the incoming link
  • identical code handles the whole list and any tail
  • short-circuit evaluation protects p^.data when p = nil
Detailed notes - 2.11.5: Working with a binary search tree

1

recursive structure makes tree operations natural to express

2

TreeNode:

  • data: longint; left and right: pointers to TreeNode
  • root := nil represents an empty tree

sum:

  • empty tree -> 0
  • otherwise SumTree(left) + data + SumTree(right)

insertion:

  • pass the root pointer by reference
  • empty subtree: allocate a node and initialize both children to nil
  • smaller value: recurse left; larger: recurse right
  • duplicate value: report ok := false; successful insertion sets ok := true

membership:

  • same branch choices; nil means absent, equality means present
  • a function suits this operation because it does not change the tree

shared search operation:

  • TreeNodePos = ^TreeNodePtr
  • SearchTree(var p, val) returns the address of the link where val is or should be
  • return @p when p = nil or p^.data = val; otherwise recurse into the appropriate child
  • var p ensures @p denotes the caller's actual root/child link

using the returned position:

  • pos^ <> nil -> value already exists
  • pos^ = nil -> insert through new(pos^) and initialize pos^^
  • shared search removes duplicated traversal logic
  • these procedures do not prevent imbalance from unfavorable insertion order

3

further tree study in the source:

  • Wirth: Algorithms and Data Structures
  • Cormen, Leiserson, and Rivest: broader algorithm coverage
  • Knuth, volume 3: sorting and searching structures

4

nonrecursive exercise:

  • search needs only a loop following the appropriate child
  • full traversal must remember ancestors and unfinished work
  • an explicit stack can store the node and its processing state, as in Hanoi

5

full iterative traversal is a harder exercise and is revisited with C

A search for an absent value ends at the null child link where insertion can attach a node.
Search chooses one subtree at each comparison. Open full size - Editable SVG

Formatting Programs

Programming style is not decoration. It makes program structure visible.

Detailed notes - 2.12: More about program layout

1

source code is read by people:

  • unclear layout makes both maintenance and writing the program harder

2

consistent formatting rules make structure visible

Book example (1 file) - 2.12: More about program layout
Book exampleBook example: treedemo.pasIn catalog
treedemo.pasPascal / 74 lines
program TreeDemo;

type
    TreeNodePtr = ^TreeNode;
    TreeNode = record
        data: longint;
        left, right: TreeNodePtr;
    end;
    TreeNodePos = ^TreeNodePtr;


function SearchTree(var p: TreeNodePtr; val: longint): TreeNodePos;
begin
    if (p = nil) or (p^.data = val) then
        SearchTree := @p
    else
    if val < p^.data then
        SearchTree := SearchTree(p^.left, val)
    else
        SearchTree := SearchTree(p^.right, val)
end;

procedure AddToTree(var p: TreeNodePtr; val: longint; var ok: boolean);
var
    pos: TreeNodePos;
begin
    pos := SearchTree(p, val);
    if pos^ = nil then
    begin
        new(pos^);
        pos^^.data := val;
        pos^^.left := nil;
        pos^^.right := nil;
        ok := true
    end
    else
        ok := false
end;

function IsInTree(p: TreeNodePtr; val: longint): boolean;
begin
    IsInTree := SearchTree(p, val)^ <> nil
end;

var
    root: TreeNodePtr = nil;
    c: char;
    n: longint;
    ok: boolean;

begin
    while not eof do
    begin
        readln(c, n);
        case c of
            '?': begin
                if IsInTree(root, n) then
                    writeln('Yes!')
                else
                    writeln('No.')
            end;
            '+': begin
                AddToTree(root, n, ok);
                if ok then
                    writeln('Successfully added')
                else
                    writeln('Couldn''t add!')
            end;
            else
                writeln('I don''t know such command! Try "+" or "?"')
        end
    end
end.

Labels and goto

Labels mark statements as jump targets and need a consistent indentation rule; outdenting a label to the surrounding block boundary makes it stand out as non-sequential control flow.

Detailed notes - 2.12.6: Labels and goto

1

goto uses ordinary statement layout

  • label placement needs an explicit convention

2

a label marks a statement, including an empty statement

  • choose its indentation and whether its statement shares the line

3

common layout:

  • label aligned with the containing structure's boundary
  • labeled statement on the next line, with ordinary body indentation
  • a nested label need not be at the file's left margin
  • a same-line statement can work when a short label leaves normal alignment intact

4

alternative:

  • indent the label together with its statement
  • either keep both on one line or put the statement below

5

outdented labels are easier to recognize as special control-flow destinations

Detailed notes - 2.12.13: Keep the rules continuously

1

maintain readable formatting from the first source line onward

2

'fix the layout later' postpones help needed while writing the program

3

code is repeatedly read during development:

  • clear indentation reduces the effort of reconstructing its structure
  • neglecting layout creates errors and wastes debugging time

4

consistent practice makes formatting habitual

5

the author's rule: restore readability before judging or extending the program

6

repair indentation immediately after moving code or adding/removing control structures

  • learn the editor's block-indent and block-unindent commands
  • adjust the whole selected block instead of inserting spaces individually

Language and Character Set

Use ASCII in source code unless there is a strong reason not to. Prefer English identifiers when the code may be read by tools, operating systems, or other programmers.

Detailed notes - 2.12.1: ASCII and English

1

the book's source-code convention uses English names and comments

2

readers work in different environments:

  • operating systems, editors, encodings, display sizes, and languages differ
  • avoid assuming that a program will never leave its original setting

3

portability assumptions adopted by the book:

  • ASCII characters, English text, and an 80-column display

4

ASCII-only source convention:

  • plain Latin letters, digits, punctuation, underscore, and whitespace
  • excludes national alphabets, accented letters, and typographic punctuation
  • the author applies this convention even to comments and literals
  • compiler acceptance alone does not establish portability across the intended tools

5

common professional language:

  • the author requires English throughout source text
  • transliteration does not solve the problem of shared understanding

6

a shared specialist language serves the same purpose across national boundaries

7

English provides access to specifications, library documentation, protocols, and technical literature

8

three source conventions:

  • identifiers: English words or abbreviations
  • comments: English
  • user interface: English or designed for translation into multiple languages

9

develop enough English to read technical material and write understandable program text

10

localization:

  • keep translated messages in external resource files
  • load and display them as data
  • source-language conventions do not restrict which languages the program can process

11

Free Pascal has facilities for internationalized programs

  • omitted from this introduction; the book later demonstrates the topic with C

Indentation

Choose one consistent indentation style and keep it everywhere:

if condition then begin
    statement1;
    statement2;
end else begin
    statement3;
end;

The indentation should show nesting. Do not rely on the editor to hide inconsistent structure.

Detailed notes - 2.12.2: Structural indentation styles

1

nested code shifts right; matching boundaries align

  • book's allowed choices: two, three, or four spaces, or one tab
  • choose once and use it throughout the program

2

tab character:

  • ASCII 9; advances to the next tab stop
  • with default width 8, one-based stops are 9, 17, 25, ...
  • one tab does not always advance exactly eight positions

3

terminal tab stops can be configured with tabs

  • the book recommends default stops so the same file displays consistently

4

editor convention prescribed here:

  • keep literal spaces and tabs distinct; avoid automatic interchange
  • tab width 8 should match ordinary terminal display
  • choose spaces if an eight-column structural indent is too wide

5

three begin/end layouts:

  • begin on its own line, aligned with the controlling statement
  • begin on the statement's line; end aligned with the statement's start
  • begin/end both shifted right, with body shifted farther
  • the book's Pascal examples use the first

6

subprogram and main-body boundaries:

  • outer begin and end each occupy their own line
  • the book places them at the left margin

if With else

In Pascal, else belongs to the nearest unmatched if. Use begin ... end when nesting could be misunderstood.

Avoid:

if a then
    if b then
        p;
    else
        q;

Make the intended structure explicit.

Detailed notes - 2.12.3: if with an else branch

1

if/else layout:

  • put each branch's statement on a separate indented line
  • align else with its if
  • for compound branches, apply the selected begin/end convention consistently
  • with same-line begin, either end else begin or a separate else begin is possible

mixed simple/compound branches:

  • an optional convention encloses both branches when either needs begin/end
  • preserves visual symmetry even if one branch contains only one statement
Detailed notes - 2.12.5: Chains of mutually exclusive if statements

1

case limitations:

  • selects by equality with ordinal constants
  • arbitrary conditions and string comparisons need if / else if / ... / else
  • mechanically increasing indentation at every else would waste width and obscure equal-rank alternatives

2

an else-if chain generalizes case:

  • its alternatives should appear at the same indentation level

3

treat else if as one layout unit:

  • same line, or consecutive lines beginning in the same column
  • apply the chosen begin/end placement consistently
  • this exception applies only when else consists of a single if
  • other nested branches use the ordinary indentation rules

Formatting case

Align alternatives and keep each branch visually separate:

case command of
    'q':
        done := true;
    'h':
        ShowHelp;
else
    writeln('unknown command');
end;
Detailed notes - 2.12.4: Layout of case statements

1

case has end without its own begin:

  • branch bodies may nevertheless require begin/end

2

case labels:

  • either align with case or indent one level
  • choose consistently for the whole program

3

same-line begin in branch bodies:

  • the book recommends indenting labels

4

begin on a new line without additional delimiter indentation:

  • the book again recommends indenting labels

5

begin/end with their own extra indentation:

  • unindented case labels avoid excessive horizontal displacement

Long Lines

Keep source lines reasonably short. Break long expressions at natural boundaries:

result :=
    first_part +
    second_part +
    third_part;
Detailed notes - 2.12.7: Maximum source width

1

80-column convention:

  • historical continuity from punched cards through printers and terminals

2

line length affects readability:

  • very narrow lines leave insufficient room for structural indentation
  • very long lines require more horizontal eye movement

3

use wide displays for larger text or multiple source windows

  • extra display width need not become extra source-line width

4

narrow tools still matter:

  • terminal editors, remote sessions, and source comparison tools

5

printing long source lines:

  • shrinking, clipping, or automatic wrapping can all reduce readability

6

book's width rule:

  • up to 75 columns: preferred
  • 76-79: allowed but undesirable
  • 80 or more: excluded by the chosen convention
  • margin leaves space for numbering and avoids ambiguity at the display edge

7

some project conventions allow exceptions for message literals:

  • keeping a message intact makes searching for its source easier

8

exceptions require judgment:

  • keep significant program behavior visible within the normal width
  • the author recommends avoiding exceptions by simplifying expressions, messages, or nesting

9

height also matters:

  • aim for subprograms readable within roughly 24-25 lines
  • modest exceptions are possible; do not rely on an unusually tall display
Detailed notes - 2.12.8: Breaking a long line

1

common problem: a long if, while, or case header

2

first simplify the condition:

  • replace a long chain of punctuation comparisons with IsPunctuation(a)
  • a well-chosen helper can express the intent and shorten the header

3

some multiline headers remain necessary

  • establish a readable convention for them

4

multiline control header:

  • break at top-level operations, usually and or or
  • indent continuation lines one level
  • use a compound body even when it contains one statement
  • put begin on its own line to separate the condition visually from the body
  • with separately indented delimiters, moving then/do/of to its own line can mark that boundary

5

same-line-begin alternative:

  • place the closing header keyword and begin together on a separate line
  • or use the ordinary standalone-begin exception for multiline headers

6

choose conventions for other long statements too

  • prevent ad hoc, inconsistent wrapping within one program

7

long assignment:

  • first try breaking after := and indenting the right-hand expression
  • break further at low-precedence operations
  • extra nesting in subexpressions gets additional indentation
  • several short terms may share a continuation line

8

short left-hand side:

  • continuation may use one extra indent or align with the first expression term
  • exact alignment is clearer but depends on the left-hand expression's length
  • the book avoids mixing tabs and spaces to obtain that alignment

9

consistent alternative: always break after := when an assignment needs wrapping

long calls:

  • break between arguments, after commas
  • continuation lines use one indent or align with the first argument

10

another call layout:

  • procedure name and opening parenthesis form the first line
  • arguments occupy indented lines; closing parenthesis returns to the original column

long declarations:

  • reconsider a subprogram needing many parameters before merely wrapping it
  • too many arguments may indicate a poor decomposition

11

parameter names are local:

  • shorten them when their meaning remains clear
  • explain necessary details in the subprogram's interface comment

12

long subprogram header:

  • procedure/function may occupy a separate unindented line
  • a function's result type can move to a separate line near the right end of the parameter list
  • otherwise wrap between parameter groups, preferably after semicolons
  • use continuation indentation, aligned groups, or a fully multiline parenthesized list

13

long string literal:

  • avoid a literal continued across physical lines with an escaped newline
  • concatenating shorter literals is possible, but makes searching for the complete message harder

14

first try shortening the message without losing its meaning

15

named string constant:

  • move a long message to a const declaration with less indentation
  • use its short name at the deeply nested call site

Separators and Spacing

Common punctuation:

Symbol Use
; Separates statements and declarations
, Separates items in lists
. Ends the whole program; also selects record fields
: Appears in declarations and in formatting output
:= Assignment
() Groups expressions and holds argument lists
[] Indexes arrays

Use spaces around binary operations and after commas. Do not add random spaces inside simple constructs such as a[i].

Detailed notes - 2.12.9: Delimiters and optional spaces

1

delimiter:

  • a token recognized independently of surrounding whitespace
  • a+b and a + b mean the same thing
  • and is different: aandb is one identifier, not a and b

2

optional spaces should support readability consistently

3

readers already have habits from ordinary prose and mathematics

4

use those habits when a program symbol serves a comparable role

5

punctuation-like separators:

  • no space before; a space after unless the line ends

6

Pascal commas, semicolons, and declaration colons:

  • follow that separator rule
  • examples: a, b; n: integer

7

dot depends on its role:

  • end. has no intervening space
  • record selection list.first has no space on either side

8

assignment := is one token:

  • surround it with spaces

9

! and ? have no operator role in the Pascal subset discussed

10

the same character may have a different role in another language:

  • C conditional colon separates expression branches
  • Lisp comma can act as an unquote operator
  • spacing should reflect that role

11

choose spacing by meaning, not merely by the printed character

12

no padding inside parentheses or brackets:

  • MyProcedure(a, b[idx + 5], c)

13

outside-parenthesis spacing in prose depends on adjacent punctuation

14

Pascal parentheses resemble mathematical notation:

  • no space between a subprogram name and its opening parenthesis
  • no space between a symbolic unary operator and its operand
  • use spaces after control keywords and before then/do/of
  • keep a closing parenthesis attached to following comma or semicolon

15

C control statements require parentheses:

  • style guides differ over spacing before them
  • the source favors the conventional space after if/while/for

16

common operator rule:

  • spaces on both sides of binary operators
  • symbolic unary operators remain attached to their operands
  • record-field dot follows its own selection notation
  • other consistent precedence-based conventions also exist

17

trailing whitespace:

  • spaces or tabs immediately before a newline are invisible clutter
  • remove them, especially when maintaining versioned source

18

splitting a statement can accidentally leave its former separating space at the line end

19

check periodically:

  • Vim search: /\s$
  • shell: grep '\s$' *.pas

Names and Case

Pascal is case-insensitive, but humans are not. Pick one convention:

MaxCount
current_index

Do not use case alone to distinguish names.

Detailed notes - 2.12.10: Choosing identifiers

1

name according to role and scope:

  • short local names are useful when context makes the meaning immediate
  • i for a loop counter; p/ptr for a pointer; str, tmp, res, sum for familiar local roles
  • conventional physical quantities may use established letters

2

globally visible names need more context:

  • a bare t could conflict between temperature and time subsystems

3

test a public name for ambiguity:

  • GetTemperature could mean reading a sensor, file, or cached value
  • ScanTemperatureSensor states the action more specifically
  • distinguish the cabin sensor from other sensors where necessary

4

length also has a cost:

  • local names usually need only a letter, abbreviation, or one/two words
  • public names commonly need two/three words
  • remove redundant words when the remaining name stays unambiguous

5

avoid excessively long identifiers with five or more words

Detailed notes - 2.12.11: Letter case

1

Pascal is case-insensitive:

  • alternate capitalization does not create distinct identifiers or keywords

2

book's default: lowercase keywords

  • uppercase outer BEGIN/END is a known optional convention

3

other capitalization conventions are possible

  • choose explicit rules and follow them throughout

4

all-uppercase keywords and arbitrary mixed case make reading harder

5

identifier convention:

  • short local names and abbreviations: lowercase
  • multiple words: capitalized word starts, as in UserListItem
  • choose a consistent rule for single-word names

Declaration Sections

A complete program often follows this order:

program name;

uses
    crt;

const
    MaxCount = 100;

type
    Index = 1..MaxCount;

var
    count: integer;

procedure Work;
begin
end;

begin
    Work;
end.

Pascal requires declarations before use more often than C does. When this becomes inconvenient, use type aliases, forward declarations, or modules.

Detailed notes - 2.12.12: Declaration sections

1

modern Pascal implementations permit repeated declaration sections and flexible ordering

2

separate program-main variables from shared globals:

  • declare main-only variables/types immediately before the main begin, after subprograms
  • declare shared variables before the subprograms that need them
  • top-level placement alone does not mean a variable should serve as shared state

3

labels belong to the body in which they are used:

  • subprogram labels are declared locally
  • main-program labels belong immediately before the main body

Testing and Debugging

Debugging as Normal Work

Debugging is not an exceptional activity. Programs are usually written, compiled, tested, corrected, and tested again many times.

Work in small increments:

Detailed notes - 2.13.1: Debugging in a programmer's work

1

debugging:

  • locating and correcting errors in a program
  • substantial newly written programs usually require it

2

debugging maxims:

  • execution follows the written program, not the author's intentions
  • a successful run does not establish correctness
  • a visible failure provides evidence that can help locate a hidden defect
  • expect mistakes, including in places that initially seem beyond suspicion

3

incorrect behavior calls for investigating what the program actually says

4

successful compilation is only one step:

  • the resulting program must still solve the requested problem

5

'finished except for debugging' can mean much work remains

6

beginners may find this discouraging after the effort of writing the first version

7

programming includes more than typing code:

  • debugging may require more time and skill than initial implementation

8

reserve time and energy for failures discovered during execution

9

plan for a working result, including debugging:

  • the author's analogy: reaching the summit is only part of returning safely

10

test individual parts as they are written:

  • recent, small pieces are easier to investigate
  • reduce dependencies so subprograms can be checked independently
  • consider how to observe and debug the code while designing it

11

localize the defect using evidence:

  • intuition is a hypothesis, not proof that one particular fragment is wrong

12

observe execution:

  • use diagnostic output and debugger stepping
  • repeatedly rereading familiar code can reproduce the same mistaken assumptions

13

rewriting without understanding the failure can reproduce the defect

14

investigate your own code before attributing a failure to the compiler or operating system

15

take responsibility for investigation:

  • a broad 'why does it not work?' provides little information
  • gather a reproducible failure and observations before seeking outside diagnosis

16

debugging can become an engaging problem-solving activity

  • treat each observation as evidence narrowing the search

Tests

A useful test set includes:

Manual tests are better than none, but saved test input files are repeatable.

Detailed notes - 2.13.2: Tests

1

running a program and observing a failure begins testing

2

ad hoc manual trials are difficult to reproduce after changes

3

retyping the same inputs wastes effort and introduces variation

4

reuse input:

  • redirect standard input or pipe data from echo
  • shell history and Ctrl-R can repeat simple trials

5

persistent test suites:

  • store cases in files instead of relying only on shell history

6

test = enough information to execute and judge a case:

  • input, invocation/setup, expected result, and a way to compare actual behavior
  • may use data files, a subprogram harness, or a separate test-driving program

7

example: reduce a fraction

  • input: integer numerator and denominator
  • output: equivalent numerator and denominator in lowest terms

8

positive examples are insufficient:

  • 25/15 -> 5/3; 7/12 -> 7/12; 100/2000 -> 1/20
  • negative operands expose assumptions hidden by those cases
  • a correction can break cases that previously worked

9

echo pipelines improve repeatability

  • manually finding commands and inspecting every result still costs time

10

four-value test record:

  • input numerator, input denominator, expected numerator, expected denominator
  • a script can execute and compare all records automatically

11

shell test driver:

  • read a b c d obtains one case at a time
  • pipe a and b into ./frcancel; capture its output in res
  • compare res with the expected c and d
  • print input, expected output, and actual output on mismatch
  • a here-document supplies the cases to the loop

12

automated suite:

  • add a case by adding a data record
  • one command runs all cases; the example reports only failures
  • tests may require effort to create but should be easy to execute

13

regression testing:

  • retain tests and rerun them after meaningful changes
  • passing old cases provides evidence against introducing old or related failures

14

simplify a failing test:

  • keep the original and create smaller variants
  • find the smallest case that still exposes the failure
  • compare failing and passing variants to isolate relevant factors

15

test first:

  • write a failing test before the implementation or correction
  • change the code until it and the previous tests pass

16

test first often targets subprograms and subsystems:

  • coverage supports safer changes
  • an unnoticed regression indicates a missing or inadequate test

17

test first is an available approach, not a requirement for every task

Book examples (3 files) - 2.13.2: Tests
Book exampleBook example: frcancel.pasIn catalog
frcancel.pasPascal / 42 lines
program CancelFraction;


type
    num = int64;

function gcd(a, b: num) : num;
begin
    while (a <> 0) and (b <> 0) do
        if a > b then
            a := a mod b
        else
            b := b mod a;
    if a = 0 then
        gcd := b
    else
        gcd := a
end;


var
    x, y, d: num;
    sign: boolean;
begin
    readln(x, y);
    if x < 0 then
    begin
        x := -x;
        sign := true
    end
    else
        sign := false;
    if y < 0 then
    begin
        sign := not sign;
        y := -y
    end;
    d := gcd(x, y);
    if sign then
        write('-');
    writeln(x div d, ' ', y div d)
end.
Book exampleBook example: frcancel_test.shIn catalog
frcancel_test.shShell / 24 lines
#!/bin/sh

OK=ok

while read a b c d ; do
    res=`echo $a $b | ./frcancel`
    if [ x"$c $d" != x"$res" ]; then
        echo TEST $a $b FAILED: expected "$c $d", got "$res"
        OK=failed
    fi
done <<EOF
   25 15 5 3
   7 12 7 12
   100 2000 1 20
EOF

if [ $OK = "ok" ]; then
   echo "Everything seems okay"
   exit 0
else
   echo "Some tests failed"
   exit 1
fi

Book exampleBook example: hanoi_test.shIn catalog
hanoi_test.shShell / 13 lines
#!/bin/sh


I=1;
while [ $I -lt 10 ]; do
    ./hanoi $I > _HAN.$I.txt
    ./a.out $I > _HAN2.$I.txt
    diff _HAN.$I.txt _HAN2.$I.txt || {
        echo FAILED for $I
        exit 1
    }
    I=$((I+1))
done

Debug Print

Temporary diagnostic output is often enough:

writeln('debug: i=', i, ' value=', a[i]);

Make debug output easy to find and remove. Do not leave accidental diagnostics in final output, especially in programs used in pipelines.

Detailed notes - 2.13.3: Diagnostic output

1

when tests expose a failure, inspect what execution actually does

2

add temporary diagnostic statements:

  • did execution reach this point?
  • what value did this variable acquire?

3

make diagnostics recognizable:

  • prefix with DEBUG, XXX, or another distinctive marker
  • finish messages with newlines
  • buffering can otherwise hide a message, especially before a crash

4

output buffering:

  • output may wait until the buffer fills, the program exits, or it is explicitly flushed
  • flush(output) forces pending standard output out
  • terminal output has additional newline/input-related flushing behavior in the model described

5

debug statements follow the same structural indentation rules as ordinary code

6

keep reusable diagnostics under conditional compilation:

  • {$DEFINE DEBUG} defines a compilation symbol
  • {$IFDEF DEBUG} ... {$ENDIF} includes the enclosed code only when it is defined
  • alternatively compile with fpc -dDEBUG myprog.pas
  • enables/disables diagnostics without editing the source each time

7

complex structures need purposeful diagnostic routines:

  • print the state of a list, tree, or table clearly
  • conditionally compile the entire diagnostic routine if appropriate

gdb

Compile with debug information:

fpc -g program.pas
gdb ./program

Common debugger commands:

Command Meaning
run Start program
break name Stop at procedure/function or line
next Step over call
step Step into call
print x Show variable
backtrace Show call stack
continue Resume execution

Use the debugger to inspect what the program actually does, not what it was intended to do.

Detailed notes - 2.13.4: The gdb debugger

1

debugger:

  • pauses execution, steps through code, and shows current values

2

debug information connects executable code with source concepts:

  • variable/subprogram names, source files, and source positions
  • without it, the debugger mostly sees machine-level information

3

compile the example with fpc -g myprog.pas

  • executable grows because it contains debugging information

4

gdb has its own command interpreter:

  • command editing, completion, and history
  • can launch a program, attach to a process, or analyze a crash dump

5

start gdb:

  • gdb ./myprog
  • gdb --args ./myprog abra schwabra kadabra supplies program arguments

6

start versus run:

  • start begins execution and stops at the main entry
  • run executes until termination, a breakpoint, or another stopping event
  • Ctrl-C interrupts the debugged program for inspection
  • a crash under the debugger exposes the current execution state

7

single-step commands:

  • next: advance at source level, running calls without entering them
  • step: enter called subprograms
  • Enter repeats the previous stepping command

8

list:

  • display source around the current position or another specified location
  • repeated listing allows inspection of a larger region

9

breakpoints:

  • break accepts a source location or subprogram name
  • stop before executing the corresponding operation
  • continue / cont resumes a paused program until the next stopping event

10

Pascal name handling:

  • the compiler/debugger combination used by the author exposes subprogram names in uppercase
  • use those names when setting breakpoints or referring to routines

11

breakpoint controls:

  • disable 3 / enable 3 toggles breakpoint 3
  • ignore 3 550 skips its next 550 hits
  • cond 5 I < 100 restricts breakpoint 5 to that condition
  • info breakpoints shows the current set and their properties

12

variable inspection and modification:

  • inspect displays a value
  • set var x:=50 changes x in the suspended program

13

backtrace / bt:

  • shows active calls, arguments, and where each call originated
  • helps reconstruct how execution reached the current routine

14

frame selection:

  • frame 1 selects the caller's context in the example
  • subsequent source listing and variable inspection use that frame

15

call:

  • invoke a program subroutine from the debugger
  • Pascal-specific value support can be limited; a string variable may work where a literal does not

16

quit or Ctrl-D exits; help describes debugger commands

17

attach to an existing process:

  • gdb ./myprogram 2765 in the source's example
  • executable supplies symbols; process supplies the live state
  • inspect calls/values, set breakpoints, and resume as needed

18

core-file analysis:

  • revisited with C
  • the Free Pascal runtime described handles many failures itself, so those failures do not produce an ordinary core dump

Modules and Separate Compilation

Large programs should be split into modules. A Pascal module is a unit.

Detailed notes - 2.14: Modules and separate compilation

1

splitting a growing program into files:

  • makes navigation and focused work easier
  • supports reuse and correction of shared components

2

textual inclusion:

  • {$I myfile.pas} inserts that file's contents at the directive

3

inclusion alone leaves one translation unit:

  • all included text is compiled together
  • repeated whole-program compilation wastes time
  • large global name sets increase collision risks

4

separate compilation:

  • divide code into modules, usually source files with related subprograms
  • compile each independently to object code
  • linker combines object files into the executable

5

module visibility:

  • export names clients need; hide internal names
  • different modules can reuse private names without exposing a conflict to clients

Units

Basic unit shape:

unit counter;

interface

procedure IncCounter;
function GetCounter: integer;

implementation

var
    value: integer;

procedure IncCounter;
begin
    value := value + 1;
end;

function GetCounter: integer;
begin
    GetCounter := value;
end;

begin
    value := 0;
end.

Use it from a program:

program demo;

uses
    counter;

begin
    IncCounter;
    writeln(GetCounter);
end.

The interface section is the public contract. The implementation section is private code and data.

Detailed notes - 2.14.1: Pascal units

1

main module versus unit:

  • main program uses program; other modules begin with unit myunit;
  • uses myunit imports its interface
  • the main program's uses follows its header and lists multiple units with commas
  • follow the filename convention mymodule.pp for unit mymodule

2

interface section:

  • exported constants, types, variables, and subprogram headers
  • subprogram bodies do not belong here

3

implementation section:

  • definitions of exported subprograms
  • private helpers, types, constants, and variables

4

interface is a contract:

  • document every exported facility and the rules for using it
  • changing existing interface behavior can break clients

5

implementation is hidden from client use:

  • may be changed while preserving the contract
  • internal design details need not enter user-facing interface documentation

6

limit exported names:

  • lowers collision risk as modules are reused in larger programs

7

private visibility also prevents accidental misuse:

  • clients cannot directly call hidden helpers or mutate hidden variables

8

encapsulation:

  • hide implementation details behind a stable, functioning interface

9

unit ends with end.

  • an optional begin ... end. initialization section runs before the main program
  • useful when unit state requires initialization

10

lngtree example:

  • export TreeNode, TreeNodePtr, AddToTree, and IsInTree
  • keep TreeNodePos and SearchTree private in implementation

client:

  • uses lngtree; initialize root := nil
  • '+' requests insertion; '?' requests membership testing

compilation:

  • fpc unitdemo.pas compiles required units automatically
  • lngtree.pp produces lngtree.ppu and lngtree.o
  • unchanged compiled units can be reused; changed source is rebuilt
  • fpc lngtree.pp also compiles the unit directly
Book examples (2 files) - 2.14.1: Pascal units
Book exampleBook example: lngtree.ppIn catalog
lngtree.ppPascal / 54 lines
unit lngtree;
interface

type
    TreeNodePtr = ^TreeNode;
    TreeNode = record
        data: longint;
        left, right: TreeNodePtr;
    end;

procedure AddToTree(var p: TreeNodePtr; val: longint; var ok: boolean);
function IsInTree(p: TreeNodePtr; val: longint): boolean;

implementation

type
    TreeNodePos = ^TreeNodePtr;

function SearchTree(var p: TreeNodePtr; val: longint): TreeNodePos;
begin
    if (p = nil) or (p^.data = val) then
        SearchTree := @p
    else
    if val < p^.data then
        SearchTree := SearchTree(p^.left, val)
    else
        SearchTree := SearchTree(p^.right, val)
end;

procedure AddToTree(var p: TreeNodePtr; val: longint;
                    var ok: boolean);
var
    pos: TreeNodePos;
begin
    pos := SearchTree(p, val);
    if pos^ = nil then
    begin
        new(pos^);
        pos^^.data := val;
        pos^^.left := nil;
        pos^^.right := nil;
        ok := true
    end
    else
        ok := false
end;

function IsInTree(p: TreeNodePtr; val: longint): boolean;
begin
    IsInTree := SearchTree(p, val)^ <> nil
end;

end.

Book exampleBook example: unitdemo.pasIn catalog
unitdemo.pasPascal / 30 lines
program UnitDemo;
uses lngtree;
var
    root: TreeNodePtr = nil;
    c: char;
    n: longint;
    ok: boolean;
begin
    while not eof do
    begin
        readln(c, n);
        case c of
            '?': begin
                if IsInTree(root, n) then
                    writeln('Yes!')
                else
                    writeln('No.')
            end;
            '+': begin
                AddToTree(root, n, ok);
                if ok then
                    writeln('Successfully added')
                else
                    writeln('Couldn''t add!')
            end;
            else
                writeln('Unknown command "', c, '"')
        end
    end
end.

Units Using Other Units

A unit can have its own uses clauses. Keep dependencies intentional:

This keeps recompilation and coupling smaller.

Detailed notes - 2.14.2: Units using other units

1

implementation dependency:

  • put uses immediately after implementation
  • imported facilities become available to internal code

2

interface dependency:

  • an exported declaration may need another unit's type or constant
  • examples: parameter/result type, array bound, or exported record-based type

3

put such uses immediately after interface

  • interface dependencies must not form a cycle

4

avoid unnecessary cross-dependencies:

  • where reciprocal use is needed, keep it in implementation sections when possible
  • interface dependencies expose more coupling to clients

Module as Architecture

A good module collects one responsibility:

The module boundary should hide representation details. Users of a stack should not need to know whether it is implemented by an array or a linked list.

Detailed notes - 2.14.3: A module as an architectural unit

1

module boundaries should follow deliberate rules

2

one module's facilities should be logically related:

  • larger programs need a comprehensible division into subsystems

3

responsibility test:

  • explain what the module/subsystem does in one phrase
  • two unrelated responsibilities suggest splitting the module

4

public name prefixes:

  • a shared subsystem prefix helps distinguish exported identifiers
  • examples: ComplexAddition, ComplexMultiplication, ComplexRealPart

Reducing Coupling

Prefer narrow interfaces:

Separate compilation is useful only when module boundaries are real design boundaries, not arbitrary file splits.

Detailed notes - 2.14.4: Reducing coupling

1

coupling = dependence between modules

  • weaker dependence generally makes modules easier to reuse and change

2

kinds of coupling:

  • one-way versus mutual dependency
  • calls: using another module's operations
  • variables: accessing its global state
  • data: multiple modules sharing the same in-memory structure
  • returning a pointer can expose shared data even without exporting a global variable

3

preferred design:

  • one-way dependencies through operations
  • avoid shared globals
  • each allocated structure has one identifiable owner responsible for its lifetime

4

practical exceptions:

  • clearly distinct subsystems can reasonably need reciprocal calls
  • merging them merely to remove the cycle may make responsibilities less clear

5

exported mutable globals spread risk:

  • any client can change them
  • failure diagnosis may require investigating the entire program
  • state private to one module limits the area that can modify it

6

representation and invariant problems:

  • exposed Cartesian coordinates make changing internal storage to polar coordinates difficult
  • operation-based interfaces can preserve client behavior through such changes
  • related state values must change together to maintain consistency
  • direct external writes bypass that control

7

dynamic shared data creates lifetime hazards:

  • one module can free a structure while another retains its address
  • assign exactly one owner to each dynamic structure
  • the owner may be a module, subsystem, or containing structure

8

ownership transfer:

  • a creator may hand a structure to its caller and retain no references
  • responsibility then belongs to the new owner

borrowing:

  • a subroutine called by the owner may use the structure during the call
  • it must not assume the structure survives afterward or retain pointers into it

9

ownership is a design convention in this Pascal model:

  • document it when the code does not make it clear
  • especially document transfers of ownership

10

coupling rules:

  • avoid mutual dependencies when doing so is straightforward
  • avoid global variables unless their benefit justifies the cost
  • minimize shared data and preserve one clear owner whenever sharing is necessary

Previous: Foundations Reading map Next: Assembly Language

Comments

Leave a comment Sign in All comments