Programs built from named pieces
In the late 1960s a movement called structured programming, led by Edsger Dijkstra, Tony Hoare and others, argued that programs should be built from small pieces, each with one job and a clear interface, combined by sequence, choice and repetition rather than by jumping around with goto. Pascal was designed to teach exactly this. Its procedures and functions are named pieces of a program, each with declared parameters and, for functions, a declared result type, and they can be nested to show which pieces belong to which.
The most important decision when you write a routine is how each parameter travels. Does the routine get its own copy? May it change the caller's variable? Is the value only an input, or only an output? Pascal makes you say so for every parameter, with the words var, const and out, and the compiler checks every call against your answer. This lesson teaches those choices, then shows how functions can themselves be passed around as values.
Routines and their parameters
Definition— Procedure and function
A procedure is called as a statement and returns nothing. A function returns a value of its declared type and is called inside expressions. Inside a function, the implicit variable Result holds the value to return (in objfpc and delphi modes); Exit(Value) sets the result and returns immediately.
| Kind | Declaration | Inside the routine | The caller passes | Use for |
|---|---|---|---|---|
| value | X: Integer | a local copy that may be changed | any expression | small inputs |
var | var X: Integer | the caller's variable itself | a variable | values to update |
const | const S: string | read-only; may be passed by reference | any expression | strings, records, arrays |
out | out X: Integer | the caller's variable, treated as uninitialised | a variable | results |
A value parameter receives a copy, so changes inside the routine are invisible to the caller. A var parameter is another name for the caller's variable: the routine can read and change it, and the caller must pass a variable, not a constant or an expression. const promises not to change the parameter, which lets the compiler pass large values such as strings and records by reference without copying. out is like var but documents that the routine only writes the parameter.
Some more features you will meet in real code:
- Default parameters:
const Greeting: string = 'Hello'may be omitted at the call. Defaults must come last in the parameter list. - Overloading: several routines may share a name if their parameter lists differ; Free Pascal marks them with the
overloaddirective (optional inobjfpcmode within one unit, but conventional, and required by Delphi). - Nesting: a routine declared inside another can see the outer routine's parameters and local variables. Pascal programmers use nesting to keep helpers next to the only code that uses them.
- Forward declarations: Pascal reads top to bottom, so a routine must be declared before it is called. When two routines call each other, declare one first with
forward;and give its body later.
Parameters in practice
program Params;
{$mode objfpc}{$H+}
{ A value parameter is a copy: changing it changes nothing outside. }
procedure Halve(X: Integer);
begin
X := X div 2;
WriteLn(' inside Halve, X = ', X);
end;
{ A var parameter is the caller's own variable. }
procedure Swap(var A, B: Integer);
var
Temp: Integer;
begin
Temp := A;
A := B;
B := Temp;
end;
{ out parameters are results; their value on entry is not used. }
procedure DivideWithRemainder(Dividend, Divisor: Integer; out Quotient, Remainder: Integer);
begin
Quotient := Dividend div Divisor;
Remainder := Dividend mod Divisor;
end;
{ const: read-only, and the compiler may avoid copying a long string. }
procedure Greet(const Name: string; const Greeting: string = 'Hello');
begin
WriteLn(Greeting, ', ', Name, '!');
end;
var
P, Q, Quot, Rem: Integer;
begin
P := 10;
Halve(P);
WriteLn('after Halve, P = ', P);
Q := 3;
Swap(P, Q);
WriteLn('after Swap, P = ', P, ', Q = ', Q);
DivideWithRemainder(47, 5, Quot, Rem);
WriteLn('47 = 5 * ', Quot, ' + ', Rem);
Greet('Mei');
Greet('Tomás', 'Hola');
end.It prints:
inside Halve, X = 5
after Halve, P = 10
after Swap, P = 3, Q = 10
47 = 5 * 9 + 2
Hello, Mei!
Hola, Tomás!Halve changed its own copy; P is still 10 afterwards. Swap has var parameters, so it exchanges the caller's variables. DivideWithRemainder gives back two results through out parameters, and Greet shows a const string parameter and a default.
The compiler enforces the parameter kinds. Calling Swap(P, 3) fails, because 3 is not a variable that Swap could change:
main.pas(11,12) Error: Variable identifier expectedAn out parameter should never be read before it is assigned. Free Pascal warns when a routine does so (Warning: Variable "X" does not seem to be initialized), and in a test the parameter still held the caller's old value 99 when read: for simple types such as Integer, out is a promise about intent, not a reset. (For managed types such as strings, out parameters are cleared on entry.)
Functions, recursion, overloading and nesting
program Funcs;
{$mode objfpc}{$H+}
{ Result is an implicit variable holding the return value. }
function Gcd(A, B: Cardinal): Cardinal;
begin
if B = 0 then
Result := A
else
Result := Gcd(B, A mod B); { recursion }
end;
{ Exit(Value) sets the result and returns at once. }
function IsPrime(N: Integer): Boolean;
var
D: Integer;
begin
if N < 2 then
Exit(False);
D := 2;
while D * D <= N do
begin
if N mod D = 0 then
Exit(False);
Inc(D);
end;
Result := True;
end;
{ Overloading: one name, different parameter lists. }
function Area(Radius: Double): Double; overload;
begin
Result := Pi * Radius * Radius;
end;
function Area(Width, Height: Double): Double; overload;
begin
Result := Width * Height;
end;
{ A nested function can use its parent's parameters and variables. }
function CountPrimesBelow(Limit: Integer): Integer;
var
N: Integer;
procedure CountIfPrime(Candidate: Integer);
begin
if IsPrime(Candidate) then
Inc(Result); { the enclosing function's Result }
end;
begin
Result := 0;
for N := 2 to Limit - 1 do
CountIfPrime(N);
end;
begin
WriteLn('Gcd(84, 36) = ', Gcd(84, 36));
WriteLn('IsPrime(97) = ', IsPrime(97), ', IsPrime(91) = ', IsPrime(91));
WriteLn('Circle of radius 2: ', Area(2.0):0:3);
WriteLn('3 x 4 rectangle: ', Area(3.0, 4.0):0:3);
WriteLn('Primes below 100: ', CountPrimesBelow(100));
end.It prints:
Gcd(84, 36) = 12
IsPrime(97) = TRUE, IsPrime(91) = FALSE
Circle of radius 2: 12.566
3 x 4 rectangle: 12.000
Primes below 100: 25Gcdis Euclid's algorithm written recursively: the gcd of A and B is the gcd of B and A mod B, and the gcd of A and 0 is A.IsPrimeusesExit(False)to leave as soon as it knows the answer. Early exits keep the main logic unindented, and experienced Pascal programmers use them freely.- The two
Areafunctions are told apart by their parameter lists. CountIfPrimeis nested insideCountPrimesBelowand increments its parent'sResult. A helper used in only one place belongs inside that place.
Older Pascal code returns a value by assigning to the function's name, Gcd := A;, which still works. Result is clearer, especially in recursive functions, where Gcd on the right of := would be read as a recursive call.
Functions as values
A procedural type describes a routine's signature, and variables and parameters of that type hold routines. This is how Pascal passes behaviour to other code: comparison functions for sorting, event handlers in GUI programs, callbacks in libraries.
program ProcTypes;
{$mode objfpc}{$H+}
type
{ A procedural type: any function from Double to Double. }
TRealFunction = function(X: Double): Double;
function Square(X: Double): Double;
begin
Result := X * X;
end;
function HalfPlusOne(X: Double): Double;
begin
Result := X / 2 + 1;
end;
{ Print a small table of any such function. }
procedure Tabulate(const Title: string; F: TRealFunction; From, Upto: Integer);
var
I: Integer;
begin
Write(Title:14, ':');
for I := From to Upto do
Write(F(I):7:2);
WriteLn;
end;
{ Find a root of F between Lo and Hi by repeated halving (bisection). }
function Bisect(F: TRealFunction; Lo, Hi: Double): Double;
var
Mid: Double;
Step: Integer;
begin
for Step := 1 to 50 do
begin
Mid := (Lo + Hi) / 2;
if (F(Lo) < 0) = (F(Mid) < 0) then
Lo := Mid
else
Hi := Mid;
end;
Result := (Lo + Hi) / 2;
end;
function TwoLess(X: Double): Double;
begin
Result := X * X - 2;
end;
begin
Tabulate('Square', @Square, 1, 5);
Tabulate('HalfPlusOne', @HalfPlusOne, 1, 5);
WriteLn('Square root of 2 by bisection: ', Bisect(@TwoLess, 0, 2):0:10);
end.It prints:
Square: 1.00 4.00 9.00 16.00 25.00
HalfPlusOne: 1.50 2.00 2.50 3.00 3.50
Square root of 2 by bisection: 1.4142135624TRealFunction is the type of any function taking and returning a Double. Tabulate and Bisect accept such a function and call it with ordinary call syntax, F(I). Bisect finds where a function crosses zero by repeatedly halving an interval that contains the crossing; applied to X² − 2 on [0, 2], it converges to √2. Note that F(I) passes an Integer where a Double is expected, which Pascal converts automatically: integers convert to reals implicitly, but reals never convert to integers without Round or Trunc.
In objfpc mode, you take a routine's address with @, as in @Square. Writing F := Sq; instead is read as a call to Sq with no arguments, and fails with Error: Wrong number of parameters specified for call to "Sq". In delphi mode the @ is optional.
Procedural types can also refer to methods of objects (function(X: Double): Double of object), which is how every button click in a Lazarus or Delphi program reaches your code; Lesson 8 shows this. Delphi also has anonymous methods, functions written inline that capture local variables (closures). Free Pascal 3.2.2 does not support them; they have been added to its development version.
How professionals write routines
A few habits distinguish professional Pascal:
- Short routines with descriptive names. A routine that needs a comment to say what it does usually needs a better name or splitting.
constfor structured inputs. Strings, records, arrays and interfaces passed by value are copied or reference-counted on every call;constavoids it and documents intent.- Functions over
varparameters when there is one result.X := Clamp(X, 0, 100)reads better thanClamp(X, 0, 100)with a hiddenvar. - No global variables for passing data. Pass what a routine needs as parameters and return what it produces, so each routine can be understood and tested alone.
- Early
Exitfor special cases, then the main logic.
Common misunderstandings
Misconception
"Changing a parameter changes the caller's variable." Only for var (and out) parameters. A forgotten var is a classic bug: the routine works on a copy and the caller sees nothing, with no error or warning.
Misconception
"Exit ends the program." It leaves the current routine. Only in the main block does it end the program. To stop the whole program from anywhere, call Halt, and do so sparingly: it skips the cleanup that callers would otherwise do.
Misconception
"const parameters are always passed by reference." The compiler decides. For small types it usually passes a copy; for large ones a reference. What const guarantees is that the routine cannot assign to the parameter.
Misconception
"A routine can call any other routine in the file." Only those declared above it, or announced with a forward declaration (or, across units, in an interface section). Pascal's single pass from top to bottom is part of why its compilers are so fast.
Exercises
All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.
1. Procedures and functions
CoreComputationalWhat does this program fragment print?
procedure Bump(X: Integer; var Y: Integer);
begin
X := X + 1;
Y := Y + X;
end;
{ ... }
A := 1; B := 10;
Bump(A, B);
Bump(A, B);
WriteLn(A, ' ', B);
2. Procedures and functions
Warm-upComputationalWhat does Gcd(1071, 462) return?
3. Procedures and functions
CoreComputationalWhat does CountPrimesBelow(50) return?
4. Procedures and functions
Warm-upComputationalWith the lesson's Greet, what does Greet('Ana', 'Olá'); print?
5. Procedures and functions
CoreHumanA procedure receives a long customer name, only reads it, and prints a label. Which declaration is best?
6. Procedures and functions
CoreComputationalWhy does Swap(P, 3); fail to compile, where Swap is procedure Swap(var A, B: Integer)?
7. Procedures and functions
StretchComputationalIn {$mode objfpc}, F is a variable of type TRealFunction. Which assignment stores the function Square in F?
8. Procedures and functions
Warm-upComputationalWhat does WriteLn(IsPrime(1), ' ', IsPrime(2)); print?
Further reading and resources
- Free Pascal Reference Guide: Using functions and proceduresParameter kinds, overloading, forward declarations, default parameters and procedural types.
- Free Pascal wikiCommunity articles on procedures, functions and procedural types.