ZetCode

Modula-2 tutorials

Modula-2 is a compiled, statically typed, imperative programming language designed by Niklaus Wirth at ETH Zurich and published in 1978. It is the successor of Pascal: it keeps Pascal's readable syntax and adds modules with separately compiled interfaces, opaque types, procedure types, coroutines, and controlled access to the machine. The language was standardised as ISO 10514 in 1996, and its ideas continued in Oberon.

GNU Modula-2

The examples in these tutorials are compiled with GNU Modula-2 (gm2), the Modula-2 front end of the GNU Compiler Collection, which has been part of GCC since version 13. On Debian and Ubuntu it comes in versioned packages such as gm2-15. The language core is taught as in Wirth's Programming in Modula-2 (PIM), with the InOut and RealInOut modules of the book; the library topics use ISO Modula-2.

Getting started

The introduction covers the history of the language, the PIM and ISO dialects, and the installation of GNU Modula-2, and compiles the first programs. The basics tutorial declares variables and constants, computes with integers and reals, prints the results with InOut and RealInOut, and writes nested comments.

Language

The program structure article takes a program module apart and compiles a first library module with a definition and an implementation part. The data types article covers integers, cardinals, reals, booleans, characters and bit sets with their ranges and sizes, and constants and literals shows how values are written in octal, hexadecimal, as character codes, and as strings.

Expressions and control flow

The operators article covers arithmetic, comparison and boolean operators and their four precedence levels, and type conversions shows how values move between characters, integers, cardinals and reals with ORD, CHR, FLOAT, TRUNC and VAL. The conditionals and loops articles choose and repeat statements with IF, CASE, WHILE, REPEAT, FOR and LOOP.

Procedures and arrays

The procedures article declares proper and function procedures with value and VAR parameters, local variables and nested procedures. Arrays groups values under one index, and open arrays passes arrays and strings of any length to one procedure. The procedure types article stores procedures in variables and passes them as parameters, for callbacks and sort comparators.

Data

The enumerations and subranges article names the values of a type and restricts a type to a range, and sets stores any combination of such values in one variable. Strings works with text in character arrays through the Strings module, and character handling classifies, converts and reads single characters. The records article groups fields of different types, builds tables from arrays of records and stores alternatives in variant records.

Pointers and modules

The pointers article allocates values on the heap with NEW and DISPOSE and links records with pointers. Modules splits a program into separately compiled definition and implementation modules, and opaque types hides the structure of a type inside its module to build abstract data types. The local modules article nests modules inside a program for information hiding without separate files.

Input and output

The console output article switches from the modules of Wirth's book to the ISO library and formats numbers with SWholeIO and SRealIO. Reading input reads lines, words and numbers and checks the read results, and files opens channels on text files with StreamFile. The command-line arguments article reads the program arguments through ProgramArgs, and environment and processes reads environment variables, runs commands and returns an exit status with the GNU-specific Environment and libc modules.

Algorithms

The recursion article writes procedures that call themselves, from factorials to permutations, and shows the limits of overflow and stack depth. Sorting implements insertion sort, quicksort and merge sort on open arrays with comparators, and searching finds values with linear and binary search. The string processing article counts, splits and trims words, parses comma-separated fields and replaces text.

Dynamic structures

The linked lists article chains records on the heap and inserts, removes and reverses nodes. The stacks, queues and trees article hides such nodes behind opaque types, and the hash tables article stores keys with linear probing in a table that grows as it fills.

Robust programs

The error handling article catches runtime errors and raises exceptions of its own with the ISO EXCEPT, RETRY and FINALLY. Compiling and debugging reads compiler messages, turns on warnings and runtime checks, follows a crash in gdb and builds with make. The unit testing article checks modules with a small test module and the exit status, and the style guide collects the conventions of the series for names, layout, imports and documentation.

Libraries

The math article computes roots, logarithms and trigonometric functions with RealMath and LongMath and calculates with complex numbers. Date and time reads the clock with SysClock and builds a small calendar module. The random numbers article rolls dice, shuffles arrays and runs simulations with the GNU RandomNumber module, and TCP/IP sockets writes a small HTTP client with ClientSocket.

Advanced

The coroutines article passes control between coroutines with TRANSFER, in the ISO and the PIM form. Processes and semaphores adds a scheduler, mutual exclusion, a bounded buffer and a deadlock. Low-level programming works with addresses, bytes and bits through the SYSTEM module, and calling C declares C functions in a DEFINITION MODULE FOR "C" and links C object files.

Applied

The calculator article builds a recursive-descent parser for arithmetic expressions from a scanner module, variant records and exceptions. Porting Pascal to Modula-2 translates Free Pascal programs side by side and points out the differences that change a program's meaning, such as MOD with negative numbers.

Language features

A Modula-2 program is a set of modules. A definition module declares what a module exports, and an implementation module holds the code; both are compiled separately, and the compiler checks every use of an imported name against its definition. The type system is strict: integers, cardinals and reals are never mixed without an explicit conversion. Input and output are not part of the language but come from library modules.

Every example in these tutorials is compiled and run with GNU Modula-2 15.2.0 before its output is shown.

last modified November 27, 2026