Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Control Flow and Procedures

Procedures and Functions in Pascal

Learn Pascal subprograms: procedures that do something, functions that return values, the Result variable, forward declarations, local variables, overloading and default parameters.

As programs grow you need to split them into named pieces. Pascal has two kinds of subprograms: a procedure performs an action, and a function computes and returns a value. Both can take parameters, own local variables and be called from anywhere below their declaration. Dividing code into well-named routines is the single most important habit for keeping programs readable.

Pascal listings are read-only here; runnable demos are C stand-ins.

Procedures

A procedure is declared before the main block, with its own begin ... end; (a semicolon, not a full stop):

PASCAL
program Greetings;

procedure SayHello;
begin
  WriteLn('Hello!');
end;

procedure Stars(count: Integer);
var
  i: Integer;
begin
  for i := 1 to count do
    Write('*');
  WriteLn;
end;

begin
  SayHello;
  Stars(5);
  Stars(2);
end.

Output:

TEXT
Hello!
*****
**

You call a procedure by writing its name, followed by arguments in parentheses if it has any. Parameters are declared like variables: name: Type. Several of the same type can share one declaration: (a, b: Integer; label: string). Variables declared inside the routine are local: they exist only while it runs.

Functions

A function returns a value, so its header names a result type:

PASCAL
function Square(x: Integer): Integer;
begin
  Result := x * x;
end;

function Average(a, b: Double): Double;
begin
  Result := (a + b) / 2;
end;

begin
  WriteLn(Square(7));           { 49 }
  WriteLn(Average(3, 4):0:1);   { 3.5 }
end.

Inside a function you set the return value with the special variable Result (Delphi and Free Pascal in Delphi/objfpc modes), or by assigning to the function's name (Square := x * x;, the original Pascal way). Prefer Result; it can be read and updated like a normal variable. Assigning to Result does not leave the function: execution continues until the end, or until you call Exit. Exit(value) sets the result and leaves at once:

PASCAL
function IsPrime(n: Integer): Boolean;
var
  d: Integer;
begin
  if n < 2 then
    Exit(False);
  for d := 2 to Trunc(Sqrt(n)) do
    if n mod d = 0 then
      Exit(False);
  Result := True;
end;

Every path should set Result; otherwise the caller receives garbage and the compiler warns that the function result "does not seem to be set".

A function call is an expression, so you can use it inside other expressions: WriteLn(Square(Square(3))) prints 81. You may also call a function as a statement and ignore its result when extended syntax is on (the default).

Calling routines inside expressions

PASCAL
var
  total: Integer;
begin
  total := Square(3) + Square(4);
  if IsPrime(total) then
    WriteLn(total, ' is prime')
  else
    WriteLn(total, ' is not prime');     { 25 is not prime }
end.

Declare before you call

The compiler reads top to bottom, so a routine must appear before the code that calls it. When two routines call each other, give the first one a forward declaration:

PASCAL
function IsOdd(n: Integer): Boolean; forward;

function IsEven(n: Integer): Boolean;
begin
  if n = 0 then Result := True
  else Result := IsOdd(n - 1);
end;

function IsOdd(n: Integer): Boolean;
begin
  if n = 0 then Result := False
  else Result := IsEven(n - 1);
end;

forward; promises the compiler the body will follow in the same block. (In the interface part of a unit, the header there plays this role; see the Units chapter.)

Overloading and defaults

Free Pascal and Delphi let several routines share a name if their parameter lists differ. Mark them with overload:

PASCAL
function Max(a, b: Integer): Integer; overload;
begin
  if a > b then Result := a else Result := b;
end;

function Max(a, b: Double): Double; overload;
begin
  if a > b then Result := a else Result := b;
end;

The compiler chooses by argument types: Max(3, 5) is the integer version, Max(2.5, 1) the real one. A parameter can also have a default value in modern Delphi and objfpc mode:

PASCAL
procedure Greet(const name: string; times: Integer = 1);
var
  i: Integer;
begin
  for i := 1 to times do
    WriteLn('Hi, ', name);
end;

begin
  Greet('Ada');        { once }
  Greet('Ada', 2);     { twice }
end.

Parameters with defaults must come last.

Functions or procedures?

flowchart TD
    A{"Does the routine<br/>produce one value?"} -->|yes| B["function<br/>use in expressions"]
    A -->|"no: it acts<br/>or returns several"| C["procedure<br/>(use var or out parameters)"]

Figure: a simple rule of thumb for choosing.

Good routines do one thing, have a descriptive verb or noun name (PrintReport, IsPrime, Average) and are short enough to read at a glance. If you cannot name a routine clearly, it probably does too much.

Stand-ins in C

C has only functions (a "procedure" is a function returning void). These programs are C.

C C stand-in: Square, Average, IsPrime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: forward declaration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a procedure and a function?

    Both can have parameters and locals. Only a function has a result type and produces a value usable in expressions.
  2. 2. How do you set a function's return value in modern Pascal?

    Assign to Result (or to the function's name in classic Pascal). Exit(value) assigns and leaves immediately.
  3. 3. What does forward; do after a routine header?

    A forward declaration lets routines call each other. The body must follow in the same declaration section.
  4. 4. What must overloaded routines have in common?

    The compiler selects the routine by the arguments' types and count, so the parameter lists must differ.

Summary

  • A procedure acts; a function returns a value through Result (or its name).
  • Declare routines before use, or use forward;.
  • Exit(value) returns early; set Result on every path.
  • overload allows one name for several parameter lists; default parameters go last.

Next: Parameters: Value, var, const and out