ZetCode

Modula-2 procedures

last modified November 27, 2026 Modula-2

A procedure gives a name to a group of statements. Modula-2 has two kinds: a proper procedure is called as a statement, and a function procedure returns a value and is called inside an expression. Both are declared with the keyword PROCEDURE, may take parameters, and may declare constants, variables and further procedures of their own.

Declaring a procedure

The simplest procedure has no parameters. Its declaration repeats the procedure name after the closing END, as a module does, and ends with a semicolon.

report.mod
MODULE report;

FROM InOut IMPORT WriteString, WriteLn;

PROCEDURE Rule;
BEGIN
  WriteString("------------------------");
  WriteLn
END Rule;

BEGIN
  Rule;
  WriteString("Monthly report: November");
  WriteLn;
  Rule;
  WriteString("No incidents reported.");
  WriteLn;
  Rule
END report.

Rule is declared between the imports and the module body. A call is the procedure name alone, without parentheses; each call runs the two statements of the body.

$ gm2 report.mod -o report
$ ./report
------------------------
Monthly report: November
------------------------
No incidents reported.
------------------------

Parameters

Parameters are listed in parentheses after the name, each with its type. Parameters of the same type may share a declaration, and groups are separated by semicolons. The call passes the arguments in the same order.

frame.mod
MODULE frame;

FROM InOut IMPORT WriteString, WriteLn, Write;

PROCEDURE Repeat(ch: CHAR; count: CARDINAL);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 1 TO count DO
    Write(ch)
  END
END Repeat;

PROCEDURE Border(width: CARDINAL);
BEGIN
  Write('+');
  Repeat('-', width);
  Write('+');
  WriteLn
END Border;

BEGIN
  Border(10);
  Write('|');
  Repeat(' ', 3);
  WriteString("Menu");
  Repeat(' ', 3);
  Write('|');
  WriteLn;
  Border(10);
  Repeat('*', 12);
  WriteLn
END frame.

Repeat writes a character a given number of times, and Border calls it to draw a line with a corner at each end. The variable i is declared inside Repeat; it exists only while the procedure runs.

$ gm2 frame.mod -o frame
$ ./frame
+----------+
|   Menu   |
+----------+
************

Function procedures

A function procedure names its result type after the parameter list. The RETURN statement ends the procedure and hands the value of its expression to the caller.

functions.mod
MODULE functions;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard;

VAR
  ticket: CARDINAL;

PROCEDURE Cube(n: INTEGER): INTEGER;
BEGIN
  RETURN n * n * n
END Cube;

PROCEDURE Average(a, b, c: INTEGER): INTEGER;
BEGIN
  RETURN (a + b + c) DIV 3
END Average;

PROCEDURE NextTicket(): CARDINAL;
BEGIN
  INC(ticket);
  RETURN ticket
END NextTicket;

BEGIN
  WriteString("Cube of -4: ");
  WriteInt(Cube(-4), 0);
  WriteLn;
  WriteString("Average: ");
  WriteInt(Average(12, Cube(2), 25), 0);
  WriteLn;
  ticket := 100;
  WriteString("Tickets:");
  WriteCard(NextTicket(), 4);
  WriteCard(NextTicket(), 4);
  WriteLn
END functions.

A call of a function procedure is an expression, so it can be an argument of another call, as Cube(2) is. A function procedure without parameters still needs empty parentheses, both in the declaration and in every call: NextTicket(). The function changes the global variable ticket, so each call returns a new number.

$ gm2 functions.mod -o functions
$ ./functions
Cube of -4: -64
Average: 15
Tickets: 101 102

Leaving with RETURN

A procedure may contain several RETURN statements. The first one that runs ends the call. In a proper procedure, RETURN stands alone, without a value.

sign.mod
MODULE sign;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

PROCEDURE Sign(n: INTEGER): INTEGER;
BEGIN
  IF n > 0 THEN
    RETURN 1
  ELSIF n < 0 THEN
    RETURN -1
  END;
  RETURN 0
END Sign;

PROCEDURE Describe(n: INTEGER);
BEGIN
  WriteInt(n, 4);
  WriteString(": ");
  IF n = 0 THEN
    WriteString("zero");
    WriteLn;
    RETURN
  END;
  IF Sign(n) > 0 THEN
    WriteString("positive")
  ELSE
    WriteString("negative")
  END;
  IF ODD(n) THEN
    WriteString(", odd")
  END;
  WriteLn
END Describe;

BEGIN
  Describe(17);
  Describe(-4);
  Describe(0)
END sign.

Sign returns from inside the IF for non-zero numbers and reaches the last RETURN only for zero. Describe handles zero first and returns early, so the rest of its body deals only with non-zero numbers. ODD is a standard function that tests whether a whole number is odd.

$ gm2 sign.mod -o sign
$ ./sign
  17: positive, odd
  -4: negative
   0: zero

A function must return a value

A function procedure that reaches its final END without a RETURN has no defined result. GNU Modula-2 does not reject such a function, so the mistake shows only when that path runs.

grades.mod
MODULE grades;

FROM InOut IMPORT WriteCard, WriteLn;

PROCEDURE Grade(points: CARDINAL): CARDINAL;
BEGIN
  IF points >= 90 THEN
    RETURN 1
  ELSIF points >= 75 THEN
    RETURN 2
  ELSIF points >= 50 THEN
    RETURN 3
  END
END Grade;

BEGIN
  WriteCard(Grade(80), 0);
  WriteLn;
  WriteCard(Grade(20), 0);
  WriteLn
END grades.

Grade forgets the case below 50 points. In the default build the second call prints whatever number happens to be left in the result register. With -fsoft-check-all the program stops at the end of the function with a message and exit status 134.

$ gm2 -fsoft-check-all grades.mod -o grades
$ ./grades
2
grades.mod:14:5: In procedure Grade
grades.mod:14:5:this function will exit without executing a RETURN statement
Aborted (core dumped)
$ echo $?
134

Results must be used

The value of a function procedure cannot be thrown away. Calling it as a statement, as if it were a proper procedure, is a compile error.

unused.mod
MODULE unused;

FROM InOut IMPORT WriteInt, WriteLn;

PROCEDURE Square(n: INTEGER): INTEGER;
BEGIN
  RETURN n * n
END Square;

BEGIN
  Square(7);
  WriteInt(Square(7), 0);
  WriteLn
END unused.

The first call of Square computes a value and does nothing with it. The compiler reports the call and points to the declared result type.

$ gm2 unused.mod -o unused
unused.mod:11:12: error: In program module ‘unused’: function ‘Square’ is being called but its return value is ignored
   11 |   Square(7);
      |            ^
unused.mod:5:11: error: function ‘Square’ return a type of ‘INTEGER’
    5 | PROCEDURE Square(n: INTEGER): INTEGER;
      |           ^~~~~~

VAR parameters

The parameters so far are value parameters: each one is a local variable that receives a copy of the argument. A parameter declared with VAR is a variable parameter; it refers to the caller's variable itself, so an assignment inside the procedure changes that variable.

swap.mod
MODULE swap;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

VAR
  x, y: INTEGER;

PROCEDURE TrySwap(a, b: INTEGER);
VAR
  t: INTEGER;
BEGIN
  t := a;
  a := b;
  b := t
END TrySwap;

PROCEDURE Swap(VAR a, b: INTEGER);
VAR
  t: INTEGER;
BEGIN
  t := a;
  a := b;
  b := t
END Swap;

BEGIN
  x := 3;
  y := 8;
  TrySwap(x, y);
  WriteString("After TrySwap: ");
  WriteInt(x, 0); WriteString(" "); WriteInt(y, 0);
  WriteLn;
  Swap(x, y);
  WriteString("After Swap:    ");
  WriteInt(x, 0); WriteString(" "); WriteInt(y, 0);
  WriteLn
END swap.

TrySwap exchanges its two copies and leaves x and y unchanged. Swap has the same body, but its VAR parameters a and b are other names for x and y during the call.

$ gm2 swap.mod -o swap
$ ./swap
After TrySwap: 3 8
After Swap:    8 3

Several results

A function procedure returns one value. A procedure that computes several values returns them through VAR parameters.

clock.mod
MODULE clock;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, Write;

PROCEDURE Split(total: CARDINAL; VAR h, m, s: CARDINAL);
BEGIN
  h := total DIV 3600;
  m := total MOD 3600 DIV 60;
  s := total MOD 60
END Split;

PROCEDURE WriteTwo(n: CARDINAL);
BEGIN
  IF n < 10 THEN
    Write('0')
  END;
  WriteCard(n, 0)
END WriteTwo;

PROCEDURE WriteTime(total: CARDINAL);
VAR
  h, m, s: CARDINAL;
BEGIN
  Split(total, h, m, s);
  WriteCard(total, 6);
  WriteString(" s = ");
  WriteCard(h, 0);
  Write(':');
  WriteTwo(m);
  Write(':');
  WriteTwo(s);
  WriteLn
END WriteTime;

BEGIN
  WriteTime(59);
  WriteTime(3725);
  WriteTime(86399)
END clock.

Split takes a number of seconds by value and stores the hours, minutes and seconds in the three VAR parameters. WriteTime passes its own local variables to it and prints them; WriteTwo adds a leading zero to one-digit numbers.

$ gm2 clock.mod -o clock
$ ./clock
    59 s = 0:00:59
  3725 s = 1:02:05
 86399 s = 23:59:59

Arguments for VAR parameters

The argument for a VAR parameter must be a variable of the same type as the parameter. Assignment compatibility is not enough: a CARDINAL variable cannot stand for an INTEGER parameter.

varargs.mod
MODULE varargs;

FROM InOut IMPORT WriteInt, WriteLn;

VAR
  level: INTEGER;
  count: CARDINAL;

PROCEDURE Double(VAR x: INTEGER);
BEGIN
  x := 2 * x
END Double;

BEGIN
  level := 5;
  count := 5;
  Double(level);
  Double(count);
  WriteInt(level, 0);
  WriteLn
END varargs.

Double(level) is correct; Double(count) is rejected, because Double would store an INTEGER in a CARDINAL variable. A constant such as Double(5) is rejected too, with the message "trying to pass a constant to a VAR parameter". GNU Modula-2 15.2 accepts an expression such as Double(level + 1) and doubles a temporary copy; Wirth's definition does not allow it.

$ gm2 varargs.mod -o varargs
<built-in>: error: formal parameter ‘INTEGER’
<built-in>: error: actual parameter ‘CARDINAL’
varargs.mod:18:10: error: 1st parameter failure due to expression incompatibility between actual parameter ‘count’ and the 1st formal ‘x’ parameter in procedure ‘Double’
   18 |   Double(count);
      |          ^~~~~

Local variables and scope

Names declared inside a procedure are local: they are visible only in that procedure. Names declared in the module are global and visible in every procedure of the module, unless a local declaration of the same name hides them.

scope.mod
MODULE scope;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

VAR
  total: CARDINAL;
  n: CARDINAL;

PROCEDURE Add(amount: CARDINAL);
BEGIN
  total := total + amount
END Add;

PROCEDURE Squares(limit: CARDINAL): CARDINAL;
VAR
  n, sum: CARDINAL;
BEGIN
  sum := 0;
  FOR n := 1 TO limit DO
    sum := sum + n * n
  END;
  RETURN sum
END Squares;

BEGIN
  total := 0;
  n := 42;
  Add(5);
  Add(Squares(3));
  WriteString("total = ");
  WriteCard(total, 0);
  WriteLn;
  WriteString("n = ");
  WriteCard(n, 0);
  WriteLn
END scope.

Add changes the global total. Squares declares its own n, which hides the global n inside the procedure, so the loop leaves the global value 42 alone. With -Wall the compiler notes the hidden name. Local variables are created anew for each call and start with no defined value, so sum must be set before it is used.

$ gm2 -Wall scope.mod -o scope
scope.mod:7:3: note: identical symbol name in two different scopes, scope ‘scope’ has symbol ‘n’
    7 |   n: CARDINAL;
      |   ^
scope.mod:16:3: note: In procedure ‘Squares’: identical symbol name in two different scopes, scope ‘Squares’ has symbol ‘n’
   16 |   n, sum: CARDINAL;
      |   ^
$ ./scope
total = 19
n = 42

Nested procedures

A procedure may declare procedures of its own. A nested procedure can be called only from the procedure that contains it, and it sees that procedure's parameters and local variables.

nested.mod
MODULE nested;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

PROCEDURE Table(base, rows: CARDINAL);
VAR
  i: CARDINAL;

  PROCEDURE Row(n: CARDINAL);
  BEGIN
    WriteCard(n, 2);
    WriteString(" x ");
    WriteCard(base, 0);
    WriteString(" =");
    WriteCard(n * base, 4);
    WriteLn
  END Row;

BEGIN
  WriteString("Table of ");
  WriteCard(base, 0);
  WriteLn;
  FOR i := 1 TO rows DO
    Row(i)
  END
END Table;

BEGIN
  Table(7, 3);
  Table(12, 4)
END nested.

Row uses the parameter base of the enclosing Table without receiving it as an argument. The nested procedure is declared after the local variables and before the BEGIN of Table; outside Table, the name Row is unknown.

$ gm2 nested.mod -o nested
$ ./nested
Table of 7
 1 x 7 =   7
 2 x 7 =  14
 3 x 7 =  21
Table of 12
 1 x 12 =  12
 2 x 12 =  24
 3 x 12 =  36
 4 x 12 =  48

Recursion and declaration order

A procedure may call itself. A Modula-2 compiler reads the whole module before it checks the calls, so a procedure can also call a procedure that is declared further down, and no forward declaration is needed.

recursion.mod
MODULE recursion;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

PROCEDURE Gcd(a, b: CARDINAL): CARDINAL;
BEGIN
  IF b = 0 THEN
    RETURN a
  END;
  RETURN Gcd(b, a MOD b)
END Gcd;

PROCEDURE IsEven(n: CARDINAL): BOOLEAN;
BEGIN
  IF n = 0 THEN
    RETURN TRUE
  END;
  RETURN IsOdd(n - 1)
END IsEven;

PROCEDURE IsOdd(n: CARDINAL): BOOLEAN;
BEGIN
  IF n = 0 THEN
    RETURN FALSE
  END;
  RETURN IsEven(n - 1)
END IsOdd;

BEGIN
  WriteString("gcd(1071, 462) = ");
  WriteCard(Gcd(1071, 462), 0);
  WriteLn;
  IF IsEven(10) AND IsOdd(7) THEN
    WriteString("10 is even and 7 is odd")
  END;
  WriteLn
END recursion.

Gcd is Euclid's algorithm: it calls itself with smaller numbers until the remainder is zero. IsEven calls IsOdd before its declaration, and the two procedures call each other until n reaches zero. Each call has its own copy of the parameters and local variables. The recursion article covers recursive procedures in detail.

$ gm2 recursion.mod -o recursion
$ ./recursion
gcd(1071, 462) = 21
10 is even and 7 is odd

Classifying numbers

The last program combines a function procedure, a procedure with VAR parameters and a procedure that reports the results. A number is perfect when the sum of its proper divisors equals the number, abundant when the sum is larger, and deficient when it is smaller.

divisors.mod
MODULE divisors;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

PROCEDURE DivisorSum(n: CARDINAL): CARDINAL;
VAR
  d, sum: CARDINAL;
BEGIN
  sum := 0;
  FOR d := 1 TO n DIV 2 DO
    IF n MOD d = 0 THEN
      INC(sum, d)
    END
  END;
  RETURN sum
END DivisorSum;

PROCEDURE Count(from, to: CARDINAL; VAR deficient, perfect, abundant: CARDINAL);
VAR
  n, s: CARDINAL;
BEGIN
  deficient := 0;
  perfect := 0;
  abundant := 0;
  FOR n := from TO to DO
    s := DivisorSum(n);
    IF s < n THEN
      INC(deficient)
    ELSIF s = n THEN
      INC(perfect);
      WriteString("perfect: ");
      WriteCard(n, 0);
      WriteLn
    ELSE
      INC(abundant)
    END
  END
END Count;

PROCEDURE Report(from, to: CARDINAL);
VAR
  d, p, a: CARDINAL;
BEGIN
  Count(from, to, d, p, a);
  WriteString("From ");
  WriteCard(from, 0);
  WriteString(" to ");
  WriteCard(to, 0);
  WriteString(": ");
  WriteCard(d, 0);
  WriteString(" deficient, ");
  WriteCard(p, 0);
  WriteString(" perfect, ");
  WriteCard(a, 0);
  WriteString(" abundant");
  WriteLn
END Report;

BEGIN
  Report(1, 100);
  Report(101, 10000)
END divisors.

DivisorSum adds every divisor up to half of the number. Count classifies a range of numbers, prints each perfect number it finds and returns three counters through VAR parameters. Report receives the counters in its local variables d, p and a and prints them.

$ gm2 divisors.mod -o divisors
$ ./divisors
perfect: 6
perfect: 28
From 1 to 100: 76 deficient, 2 perfect, 22 abundant
perfect: 496
perfect: 8128
From 101 to 10000: 7432 deficient, 2 perfect, 2466 abundant

Next steps

The procedures in this article work on single values. The arrays article groups many values of one type under one name and passes them to procedures.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared proper procedures and function procedures in Modula-2, passed value and VAR parameters, left procedures with RETURN, used local variables and nested procedures, and written recursive procedures. The loops and conditionals articles cover the statements used in the procedure bodies.

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 Modula-2 tutorials.