ZetCode

Procedural types and callbacks in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

In Pascal a procedure or a function is not only a piece of code that is called by name: it is also a value with a type. A procedural type describes the parameter list and the result of a routine, and a variable of that type can hold one routine at a time. That makes callbacks, dispatch tables, and plug-in-style designs possible without classes. This article declares procedure and function types, passes them as callbacks, stores them in a table, works with method pointers, and shows why an unassigned procedural variable must be tested with Assigned.

Declaring a procedural type

A procedural type is written like the header of a procedure or function without a name. TIntProc = procedure(X: Integer) describes any procedure that takes one integer and returns nothing, and TIntFunc = function(X: Integer): Integer describes a function with one integer parameter and an integer result. A variable of such a type stores the address of a routine, and the routine is attached with the @ operator. Calling the variable calls whichever routine is currently attached.

proctype.pas
program proctype;
{$mode objfpc}{$H+}

type
  TIntProc = procedure(X: Integer);

procedure ShowDouble(X: Integer);
begin
  WriteLn(X, ' doubled is ', X * 2);
end;

procedure ShowSquare(X: Integer);
begin
  WriteLn(X, ' squared is ', X * X);
end;

var
  P: TIntProc;

begin
  P := @ShowDouble;
  P(5);
  P := @ShowSquare;
  P(5);
end.

The variable P is reassigned between the two calls, so the same expression P(5) runs two different routines. The type check happens at compile time: assigning ShowSquare, which takes one integer, to P is allowed, while a routine with a different parameter list would be rejected. The @ operator is required in ObjFPC mode; without it the compiler reads the name as a call and reports a parameter error, so the explicit address is not optional here.

$ fpc -gl proctype.pas
$ ./proctype
5 doubled is 10
5 squared is 25

Callbacks

A routine that receives a procedural value can call it without knowing which routine it is. This is a callback: the caller supplies the behaviour, and the receiving routine supplies the control flow. The example below applies a function to every element of an array. ApplyToAll contains the loop, and the operation is a parameter, so doubling and tripling reuse the same loop.

callback.pas
program callback;
{$mode objfpc}{$H+}

type
  TIntFunc = function(X: Integer): Integer;

function DoubleIt(X: Integer): Integer;
begin
  Result := X * 2;
end;

function TripleIt(X: Integer): Integer;
begin
  Result := X * 3;
end;

procedure ApplyToAll(F: TIntFunc; const Data: array of Integer);
var
  I: Integer;
begin
  for I := Low(Data) to High(Data) do
  begin
    if I > Low(Data) then
      Write(' ');
    Write(F(Data[I]));
  end;
  WriteLn;
end;

var
  Data: array[0..4] of Integer = (1, 2, 3, 4, 5);

begin
  Write('double: ');
  ApplyToAll(@DoubleIt, Data);
  Write('triple: ');
  ApplyToAll(@TripleIt, Data);
end.

The parameter F has the procedural type, and the call F(Data[I]) inside the loop is an indirect call through the stored address. The open-array parameter Data accepts any array of integers, so the same callback routine could be applied to data of any length. The compiler cannot inline the call because the target is only known at run time, which is the price of the flexibility.

$ fpc -gl callback.pas
$ ./callback
double: 2 4 6 8 10
triple: 3 6 9 12 15

A table of functions

Because procedural values can be stored in arrays and records, a program can build a dispatch table: a collection of named operations that is searched at run time instead of being written as a long case statement. Each entry pairs a name with a function, and the caller looks up the name and calls the result. Adding an operation means adding a table entry, not changing the dispatcher.

table.pas
program table;
{$mode objfpc}{$H+}

type
  TBinFunc = function(A, B: Integer): Integer;
  TOperation = record
    Name: string;
    Fn: TBinFunc;
  end;

function Add(A, B: Integer): Integer;
begin
  Result := A + B;
end;

function Subtract(A, B: Integer): Integer;
begin
  Result := A - B;
end;

function Multiply(A, B: Integer): Integer;
begin
  Result := A * B;
end;

var
  Ops: array[0..2] of TOperation;
  I: Integer;

begin
  Ops[0].Name := 'add'; Ops[0].Fn := @Add;
  Ops[1].Name := 'sub'; Ops[1].Fn := @Subtract;
  Ops[2].Name := 'mul'; Ops[2].Fn := @Multiply;

  for I := Low(Ops) to High(Ops) do
    WriteLn(Ops[I].Name, '(7, 3) = ', Ops[I].Fn(7, 3));
end.

The record combines data and behaviour: the Name field is used for display and lookup, and Fn is the operation itself. The loop does not know which function it calls on each pass. In a real program the search would compare the user's word with Ops[I].Name and call only the matching entry; the table replaces a chain of if statements and keeps the operations in one place.

$ fpc -gl table.pas
$ ./table
add(7, 3) = 10
sub(7, 3) = 4
mul(7, 3) = 21

Method pointers

A method belongs to an object and needs both the code address and the object instance. Pascal expresses that with the of object suffix on a procedural type. A method pointer can be assigned from an object's method and called later, and the compiler passes the hidden Self reference automatically. Events in Delphi and Lazarus are built on exactly this mechanism.

methodptr.pas
program methodptr;
{$mode objfpc}{$H+}

uses SysUtils;

type
  TGreeter = class
  private
    FName: string;
  public
    constructor Create(const AName: string);
    procedure Hello(Level: Integer);
  end;

  TLevelProc = procedure(Level: Integer) of object;

constructor TGreeter.Create(const AName: string);
begin
  FName := AName;
end;

procedure TGreeter.Hello(Level: Integer);
begin
  WriteLn('Hello ', FName, ' (level ', Level, ')');
end;

var
  G: TGreeter;
  M: TLevelProc;
  Raw: TMethod;

begin
  G := TGreeter.Create('Ada');
  try
    M := @G.Hello;
    M(1);

    Raw := TMethod(M);
    WriteLn('code assigned: ', Assigned(Raw.Code));
    WriteLn('data assigned: ', Assigned(Raw.Data));
  finally
    G.Free;
  end;
end.

TMethod is the two-field record behind every method pointer: Code holds the address of the method and Data holds the Self pointer. TMethod(M) reinterprets the method pointer as that record, which is useful for low-level code and for libraries that need to pass a method as an untyped pair of pointers. The object must stay alive for as long as the method pointer is used, because the pointer does not keep it alive; here the try..finally block frees it after the last call.

$ fpc -gl methodptr.pas
$ ./methodptr
Hello Ada (level 1)
code assigned: TRUE
data assigned: TRUE

Nil checks with Assigned

A procedural variable is a pointer, and its initial value is nil. Calling a nil procedural variable does not raise a Pascal exception: it jumps to address zero and the process stops with a segmentation fault. The Assigned function returns False for a nil procedural variable and True otherwise, so every callback that may be optional should be tested before it is called.

nilcheck.pas
program nilcheck;
{$mode objfpc}{$H+}

type
  TIntFunc = function(X: Integer): Integer;

function DoubleIt(X: Integer): Integer;
begin
  Result := X * 2;
end;

var
  F: TIntFunc;

begin
  F := nil;
  if not Assigned(F) then
    WriteLn('F is not assigned');

  F := @DoubleIt;
  if Assigned(F) then
    WriteLn('F(21) = ', F(21));

  F := nil;
  if not Assigned(F) then
    WriteLn('F is nil again');
end.

Assigned also accepts object references and class references, and it is the standard guard before Free or before calling an event handler that a caller may not have supplied. The check is cheap: it compares the pointer with nil. The program assigns nil before the first test; global variables start with that value anyway, but the explicit assignment documents the state and avoids a compiler warning about an uninitialized variable. Assigning nil after use makes the "not assigned" state explicit and prevents a stale pointer from being called by mistake.

$ fpc -gl nilcheck.pas
$ ./nilcheck
F is not assigned
F(21) = 42
F is nil again

Next steps

Procedural types reappear throughout the rest of the series: the sorting article passes comparers to library sorts, and the numerical integration article passes the function to integrate as a parameter. The procedures and functions article describes parameter modes and open arrays, which the callbacks above rely on, and the classes article introduces the objects whose methods are used as method pointers.

Source

Free Pascal Reference guide: procedural types

Free Pascal: Assigned

Free Pascal: TMethod

In this article we declared procedure and function types, passed them as callbacks, stored them in a dispatch table, used method pointers with of object, inspected TMethod, and guarded nil values with Assigned. The series continues with enumerations and sets in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.