Porting Pascal to Modula-2
last modified November 27, 2026 Modula-2
Modula-2 is Wirth's successor to Pascal, so a Pascal program ports to it
almost line by line. Most of the work is mechanical: keywords become upper
case, begin disappears from inside statements, and output goes
through imported procedures. A few differences change the meaning of a
program, though, and those are worth knowing before the first port.
Each section shows a small Free Pascal program and its Modula-2
translation, then runs both. The Pascal programs use the
objfpc mode of Free Pascal 3.2.2, as in the
Pascal tutorial; the Modula-2 programs are compiled
with gm2 -fiso and use the ISO library. The
introduction lists the differences in brief.
A first program
A Pascal program has a program heading and a main block that
ends with a full stop. Modula-2 has a MODULE heading instead,
and the name is repeated at the end.
program greeting;
{$mode objfpc}{$H+}
begin
WriteLn('Hello there!');
end.
The {$mode objfpc}{$H+} line selects the Free Pascal dialect; it has no counterpart in the Modula-2 version, where the dialect is chosen by the -fiso option.
MODULE greeting;
FROM STextIO IMPORT WriteString, WriteLn;
BEGIN
WriteString("Hello there!"); WriteLn
END greeting.
Keywords and standard identifiers are upper case in Modula-2, and every
name is case-sensitive: writeln, WriteLn and
WRITELN are the same procedure in Pascal but three different
names in Modula-2. WriteLn is not built into the language; it
comes from the library module STextIO and must be imported.
WriteString takes one string, so a Pascal
WriteLn with several arguments becomes several calls. Strings
may be written in double or single quotes. The semicolon separates
statements in both languages, so it is not needed before
END.
$ fpc -gl greeting.pas $ ./greeting Hello there! $ gm2 -fiso greeting.mod -o greeting $ ./greeting Hello there!
Numbers and formatted output
Pascal formats numbers in WriteLn with :width and
:width:decimals. Modula-2 has a separate procedure for each
type, and the width is a parameter.
program prices;
{$mode objfpc}{$H+}
var
count: Integer;
price: Real;
begin
count := 3;
price := 12.5;
WriteLn('items: ', count:4);
WriteLn('price: ', price:8:2);
WriteLn('total: ', count * price:8:2);
end.
WriteLn takes any mix of strings and numbers, each with an optional format.
MODULE prices;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM SRealIO IMPORT WriteFixed;
VAR
count: INTEGER;
price: REAL;
BEGIN
count := 3;
price := 12.5;
WriteString("items: "); WriteInt(count, 4); WriteLn;
WriteString("price: "); WriteFixed(price, 2, 8); WriteLn;
WriteString("total: "); WriteFixed(FLOAT(count) * price, 2, 8); WriteLn
END prices.
count:4 becomes WriteInt(count, 4) from
SWholeIO, and price:8:2 becomes
WriteFixed(price, 2, 8) from SRealIO: the
decimals come before the width. The bigger change is in the total. Pascal
converts the integer count to a real number silently when it
meets price; Modula-2 never mixes types in an expression, so
the conversion is written out with FLOAT. Even a literal must
have the right type: FLOAT(count) / 2 is rejected with
"expression of type ‘REAL’ is incompatible", and 2.0 is
needed. The type conversions
article lists the conversion functions.
$ fpc -gl prices.pas $ ./prices items: 3 price: 12.50 total: 37.50 $ gm2 -fiso prices.mod -o prices $ ./prices items: 3 price: 12.50 total: 37.50
Division and remainder
Both languages have DIV and MOD for whole
numbers, but with a negative operand they can give different results.
This is the one difference in this article that a port does not reveal
with a compiler error.
program division;
{$mode objfpc}{$H+}
var
a, b: Integer;
begin
a := -7;
b := 2;
WriteLn(a, ' div ', b, ' = ', a div b);
WriteLn(a, ' mod ', b, ' = ', a mod b);
WriteLn(a, ' / ', b, ' = ', a / b:0:1);
end.
The Pascal program prints the quotient, the remainder and the real quotient of -7 and 2.
MODULE division;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM SRealIO IMPORT WriteFixed;
VAR
a, b: INTEGER;
PROCEDURE Show(op: ARRAY OF CHAR; result: INTEGER);
BEGIN
WriteInt(a, 0); WriteString(op); WriteInt(b, 0);
WriteString(" = "); WriteInt(result, 0); WriteLn
END Show;
BEGIN
a := -7;
b := 2;
Show(" DIV ", a DIV b);
Show(" MOD ", a MOD b);
Show(" REM ", a REM b);
WriteInt(a, 0); WriteString(" / "); WriteInt(b, 0); WriteString(" = ");
WriteFixed(FLOAT(a) / FLOAT(b), 1, 0); WriteLn
END division.
Free Pascal truncates toward zero, as C does: -7 div 2 is -3 and the
remainder -1 has the sign of the dividend. GNU Modula-2 divides so that
MOD is never negative: -7 DIV 2 is -4 and -7 MOD 2 is 1. The
truncating remainder of Pascal is REM, an ISO operator. A
port of code that may see negative numbers should replace
mod with REM and check every div.
The / operator is another trap: on two integers gm2 accepts
it without a warning and truncates (7 / 2 is 3), while Pascal
returns the real number 3.5. Convert the operands with FLOAT
first. The operators article covers the
rules.
$ fpc -gl division.pas $ ./division -7 div 2 = -3 -7 mod 2 = -1 -7 / 2 = -3.5 $ gm2 -fiso division.mod -o division $ ./division -7 DIV 2 = -4 -7 MOD 2 = 1 -7 REM 2 = -1 -7 / 2 = -3.5
Statements closed by END
In Pascal, if, while and for
control one statement, and a group needs begin and
end. In Modula-2 every structured statement holds a sequence
of statements and ends with its own END.
program scores;
{$mode objfpc}{$H+}
var
score, passed: Integer;
begin
passed := 0;
score := 45;
while score <= 100 do
begin
Write(score:3, ' ');
if score >= 90 then
begin
passed := passed + 1;
WriteLn('excellent');
end
else if score >= 60 then
begin
passed := passed + 1;
WriteLn('passed');
end
else
WriteLn('failed');
score := score + 15;
end;
WriteLn(passed, ' passed');
end.
Both branches of the first two if statements need begin and end, because each holds two statements.
MODULE scores;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
score, passed: INTEGER;
BEGIN
passed := 0;
score := 45;
WHILE score <= 100 DO
WriteInt(score, 3); WriteString(" ");
IF score >= 90 THEN
INC(passed);
WriteString("excellent")
ELSIF score >= 60 THEN
INC(passed);
WriteString("passed")
ELSE
WriteString("failed")
END;
WriteLn;
INC(score, 15)
END;
WriteInt(passed, 0); WriteString(" passed"); WriteLn
END scores.
The begin/end pairs disappear and
else if becomes ELSIF, so the chain needs a
single END. The classic Pascal mistake, a semicolon before
else, cannot happen, and neither can a dangling
else. score := score + 15 may stay, but
INC(score, 15) is the usual Modula-2 form. REPEAT
… UNTIL is the same in both languages. Pascal's
break has a counterpart only in LOOP, where
EXIT leaves the loop; there is no continue. The
loops article shows the loop forms.
$ fpc -gl scores.pas $ ./scores 45 failed 60 passed 75 passed 90 excellent 3 passed $ gm2 -fiso scores.mod -o scores $ ./scores 45 failed 60 passed 75 passed 90 excellent 3 passed
The CASE statement
The case statement looks almost the same, but the branches
are separated differently.
program days;
{$mode objfpc}{$H+}
var
day: Integer;
begin
for day := 5 to 8 do
case day of
1..5: WriteLn(day, ' workday');
6, 7: WriteLn(day, ' weekend');
else
WriteLn(day, ' no such day');
end;
end.
The for loop controls a single case statement, so it needs no begin.
MODULE days;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
day: INTEGER;
BEGIN
FOR day := 5 TO 8 DO
WriteInt(day, 0);
CASE day OF
1..5: WriteString(" workday") |
6, 7: WriteString(" weekend")
ELSE
WriteString(" no such day")
END;
WriteLn
END
END days.
In Pascal each branch is one statement ended by a semicolon. In Modula-2
the branches are separated by |, and each may hold a sequence
of statements, so no begin is needed. Labels, ranges and the
ELSE part are written as in Free Pascal. When no label
matches and there is no ELSE, both programs do nothing by
default; compiled with -fsoft-check-all, the Modula-2 program
stops with "this CASE statement does not have an ELSE statement". The
conditionals article covers
CASE.
$ fpc -gl days.pas $ ./days 5 workday 6 weekend 7 weekend 8 no such day $ gm2 -fiso days.mod -o days $ ./days 5 workday 6 weekend 7 weekend 8 no such day
Procedures and functions
Modula-2 has no function keyword. A procedure with a result
type is a function procedure, and it returns its value with
RETURN.
program params;
{$mode objfpc}{$H+}
function Average(a, b: Integer): Real;
begin
Result := (a + b) / 2;
end;
procedure Exchange(var a, b: Integer);
var
t: Integer;
begin
t := a;
a := b;
b := t;
end;
var
x, y: Integer;
begin
x := 3;
y := 8;
Exchange(x, y);
WriteLn(x, ' ', y);
WriteLn(Average(x, y):0:1);
end.
Average sets Result, and Exchange swaps its two var parameters.
MODULE params;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM SRealIO IMPORT WriteFixed;
PROCEDURE Average(a, b: INTEGER): REAL;
BEGIN
RETURN FLOAT(a + b) / 2.0
END Average;
PROCEDURE Exchange(VAR a, b: INTEGER);
VAR
t: INTEGER;
BEGIN
t := a;
a := b;
b := t
END Exchange;
VAR
x, y: INTEGER;
BEGIN
x := 3;
y := 8;
Exchange(x, y);
WriteInt(x, 0); WriteString(" "); WriteInt(y, 0); WriteLn;
WriteFixed(Average(x, y), 1, 0); WriteLn
END params.
Pascal's Result :=, or an assignment to the function name,
becomes RETURN, which also ends the procedure at once, like
Exit(value). The name of the procedure is repeated after its
END. VAR parameters work as in Pascal. A
procedure without parameters is called without parentheses, but a function
procedure without parameters needs them: Next(), not
Next. Default parameter values and overloading do not exist,
so overloaded Pascal routines need different names. See the
procedures article.
$ fpc -gl params.pas $ ./params 8 3 5.5 $ gm2 -fiso params.mod -o params $ ./params 8 3 5.5
Open arrays
A Free Pascal array of Integer parameter, an open array,
exists in Modula-2 too; Wirth introduced it there. Typed array constants
become structured constants.
program totals;
{$mode objfpc}{$H+}
function Sum(const a: array of Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i := Low(a) to High(a) do
Result := Result + a[i];
end;
const
Primes: array[1..5] of Integer = (2, 3, 5, 7, 11);
var
squares: array[1..4] of Integer;
k: Integer;
begin
for k := 1 to 4 do
squares[k] := k * k;
WriteLn(Sum(Primes));
WriteLn(Sum(squares));
end.
Sum accepts arrays of any length; Low and High give the bounds of the parameter.
MODULE totals;
FROM STextIO IMPORT WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Sum(a: ARRAY OF INTEGER): INTEGER;
VAR
i: CARDINAL;
total: INTEGER;
BEGIN
total := 0;
FOR i := 0 TO HIGH(a) DO
total := total + a[i]
END;
RETURN total
END Sum;
TYPE
Five = ARRAY [1..5] OF INTEGER;
CONST
Primes = Five{2, 3, 5, 7, 11};
VAR
squares: ARRAY [1..4] OF INTEGER;
k: INTEGER;
BEGIN
FOR k := 1 TO 4 DO
squares[k] := k * k
END;
WriteInt(Sum(Primes), 0); WriteLn;
WriteInt(Sum(squares), 0); WriteLn
END totals.
In both languages an open array is indexed from 0, whatever the bounds of
the actual array. High(a) becomes HIGH(a); there
is no Low, because it is always 0, and the index is a
CARDINAL. A Pascal typed constant such as
Primes becomes an ISO structured constant: the type name
followed by the values in braces, which needs a named array type. Two
Modula-2 rules have no Pascal equivalent: arrays cannot be compared with
=, and an open array cannot be assigned to a fixed one. The
open arrays article covers them.
$ fpc -gl totals.pas $ ./totals 28 30 $ gm2 -fiso totals.mod -o totals $ ./totals 28 30
Strings
Free Pascal's string type grows as needed and supports
+ and =. Modula-2 has no string type: a string is
an ARRAY OF CHAR of fixed size, ended by 0C when
it is shorter than the array.
program names;
{$mode objfpc}{$H+}
var
first, last, full: string;
begin
first := 'Niklaus';
last := 'Wirth';
full := first + ' ' + last;
WriteLn(full, ' has ', Length(full), ' characters');
WriteLn('initials: ', first[1], last[1]);
if full = 'Niklaus Wirth' then
WriteLn('the names match');
end.
The Pascal string is concatenated with +, compared with = and indexed from 1.
MODULE names;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Assign, Concat, Append, Length, Equal;
VAR
first, last, full: ARRAY [0..39] OF CHAR;
BEGIN
Assign("Niklaus", first);
Assign("Wirth", last);
Concat(first, " ", full);
Append(last, full);
WriteString(full); WriteString(" has ");
WriteCard(Length(full), 0); WriteString(" characters"); WriteLn;
WriteString("initials: "); WriteChar(first[0]); WriteChar(last[0]);
WriteLn;
IF Equal(full, "Niklaus Wirth") THEN
WriteString("the names match"); WriteLn
END
END names.
Every string operation becomes a procedure call from the ISO
Strings module: assignment of a literal is
Assign, + is Concat or
Append, = is Equal, and
Length keeps its name. The procedures truncate silently when
the destination is too small, so the arrays must be sized for the longest
text. Characters are counted from 0, not 1: Pascal's
first[1] is first[0]. The
string processing article shows
more of the module.
$ fpc -gl names.pas $ ./names Niklaus Wirth has 13 characters initials: NW the names match $ gm2 -fiso names.mod -o names $ ./names Niklaus Wirth has 13 characters initials: NW the names match
Records and pointers
Records and pointers port with few changes. The heap procedures have the same names, but in Modula-2 they need storage procedures in scope.
program stack;
{$mode objfpc}{$H+}
type
PNode = ^TNode;
TNode = record
value: Integer;
next: PNode;
end;
var
head, p: PNode;
i: Integer;
begin
head := nil;
for i := 1 to 3 do
begin
New(p);
p^.value := i * 10;
p^.next := head;
head := p;
end;
while head <> nil do
begin
p := head;
Write(p^.value, ' ');
head := head^.next;
Dispose(p);
end;
WriteLn;
end.
The program pushes three nodes onto a list and pops them again, freeing each one.
MODULE stack;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Node = POINTER TO NodeRec;
NodeRec = RECORD
value: INTEGER;
next: Node
END;
VAR
head, p: Node;
i: INTEGER;
BEGIN
head := NIL;
FOR i := 1 TO 3 DO
NEW(p);
p^.value := i * 10;
p^.next := head;
head := p
END;
WHILE head # NIL DO
p := head;
WriteInt(p^.value, 0); WriteString(" ");
head := head^.next;
DISPOSE(p)
END;
WriteLn
END stack.
^TNode becomes POINTER TO NodeRec, and the
pointer type may refer to a record declared after it, as in Pascal.
Modula-2 does not use the T and P prefixes; the
pointer usually gets the short name. NEW and
DISPOSE are translated into calls of
ALLOCATE and DEALLOCATE, so these must be
imported from Storage; without the import the compiler
reports "ALLOCATE procedure not found for NEW substitution".
<> may stay or become #. The
pointers article explains the heap.
$ fpc -gl stack.pas $ ./stack 30 20 10 $ gm2 -fiso stack.mod -o stack $ ./stack 30 20 10
Units and modules
A Pascal unit has an interface part and an
implementation part in one file. In Modula-2 the two parts are
separate files: a definition module and an implementation module.
unit temps;
{$mode objfpc}{$H+}
interface
function ToFahrenheit(c: Real): Real;
implementation
function ToFahrenheit(c: Real): Real;
begin
Result := c * 9 / 5 + 32;
end;
initialization
WriteLn('temps ready');
end.
Free Pascal compiles the unit into temps.ppu and
temps.o. Its initialization section runs before
the main program.
program weather;
{$mode objfpc}{$H+}
uses
temps;
begin
WriteLn(ToFahrenheit(21.5):0:1);
WriteLn(ToFahrenheit(-40):0:1);
end.
The program names the unit in its uses clause and Free Pascal
compiles the unit on its own.
DEFINITION MODULE Temps; PROCEDURE ToFahrenheit(c: REAL): REAL; END Temps.
The definition module holds the interface part: the
procedure headings, constants and types that clients may use.
IMPLEMENTATION MODULE Temps;
FROM STextIO IMPORT WriteString, WriteLn;
PROCEDURE ToFahrenheit(c: REAL): REAL;
BEGIN
RETURN c * 9.0 / 5.0 + 32.0
END ToFahrenheit;
BEGIN
WriteString("Temps ready"); WriteLn
END Temps.
The implementation module holds the code. The initialization
section of the unit becomes the body of the module, which runs before the
program that imports it.
MODULE weather; FROM STextIO IMPORT WriteLn; FROM SRealIO IMPORT WriteFixed; FROM Temps IMPORT ToFahrenheit; BEGIN WriteFixed(ToFahrenheit(21.5), 1, 0); WriteLn; WriteFixed(ToFahrenheit(-40.0), 1, 0); WriteLn END weather.
uses temps becomes an import list, and only the names listed
there are visible; IMPORT Temps instead would require
qualified names such as Temps.ToFahrenheit. gm2 does not
compile imported modules by itself: the implementation module is compiled
with -c and its object file is linked with the program. The
literals in ToFahrenheit became 9.0,
5.0 and 32.0, and -40 became
-40.0, because a whole literal is not a real. The
modules article covers separate
compilation.
$ fpc -gl weather.pas $ ./weather temps ready 70.7 -40.0 $ gm2 -fiso -c Temps.mod $ gm2 -fiso weather.mod Temps.o -o weather $ ./weather Temps ready 70.7 -40.0
Text files
Pascal file handling is built into the language: TextFile,
Reset, ReadLn and Eof. In ISO
Modula-2 a file is a channel opened with StreamFile and read
with TextIO. The programs number the lines of a short file.
program lines;
{$mode objfpc}{$H+}
var
f: TextFile;
line: string;
n: Integer;
begin
AssignFile(f, 'note.txt');
Reset(f);
n := 0;
while not Eof(f) do
begin
ReadLn(f, line);
n := n + 1;
WriteLn(n:2, ': ', line);
end;
CloseFile(f);
end.
AssignFile and Reset open the file, and Eof is tested before each ReadLn.
MODULE lines;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Strings IMPORT Length;
VAR
f: ChanId;
res: OpenResults;
line: ARRAY [0..255] OF CHAR;
n: INTEGER;
BEGIN
Open(f, "note.txt", read, res);
IF res # opened THEN
WriteString("cannot open note.txt"); WriteLn
ELSE
n := 0;
LOOP
ReadString(f, line);
IF (ReadResult(f) = endOfInput) AND (Length(line) = 0) THEN
EXIT
END;
INC(n);
WriteInt(n, 2); WriteString(": "); WriteString(line); WriteLn;
SkipLine(f)
END;
Close(f)
END
END lines.
Open reports failure in res instead of stopping
the program with a run-time error, so the check is part of the port.
Modula-2 has no Eof to test before reading: the loop reads
first and then asks ReadResult whether the end of input was
reached. ReadString stops at the end of the line and
SkipLine moves past it, which together do the work of
ReadLn. The files article
explains the channels.
$ cat note.txt Modula-2 came out of the Lilith project. The workstation and its operating system were written in the new language. $ fpc -gl lines.pas $ ./lines 1: Modula-2 came out of the Lilith project. 2: The workstation and its operating system 3: were written in the new language. $ gm2 -fiso lines.mod -o lines $ ./lines 1: Modula-2 came out of the Lilith project. 2: The workstation and its operating system 3: were written in the new language.
What has no direct equivalent
Some Pascal features need more than a translation:
- Exceptions: Free Pascal's
try … exceptandraisebecome anEXCEPTpart of a procedure andEXCEPTIONS.RAISE; there is no exception class hierarchy. See error handling. - Classes and objects (
objfpcmode) have no counterpart. An abstract data type in a module with an opaque type covers many uses, and procedure types stand in for virtual methods. - Dynamic arrays and
SetLength: Modula-2 arrays have fixed bounds; a growing table allocates memory itself, as in the hash tables article. gotoand labels do not exist.LOOPwithEXIT, orRETURN, replaces them.Inc,Dec,Ord,Chr,High,IncludeandExcludebecomeINC,DEC,ORD,CHR,HIGH,INCLandEXCL.Roundhas no counterpart ("procedure function ‘ROUND’ is undefined");TRUNCand the ISOINTtruncate.- Sets port directly (
SET OF,IN,+,-,*). Free Pascal limits a set to 256 elements; gm2 accepts larger ones, such asSET OF [0..9999]. See the sets article.
Source
Modula-2 reference at modula2.org
In this article we have ported Free Pascal programs to Modula-2: the
program heading and imports, formatted output and explicit conversions,
DIV, MOD and REM with negative
numbers, statements closed by END, CASE,
function procedures with RETURN, open arrays, strings as
character arrays, pointers, units as definition and implementation
modules, and text files. The style
guide shows how the ported code should look, and the
calculator article is a larger program
in the same style.
Author
List all Modula-2 tutorials.