ZetCode

Modula-2 records

last modified November 26, 2026 Modula-2

A record groups values of different types under one name, such as the title, year and edition of a book. Each value is a field with a name of its own. Records are the main way to describe data in Modula-2: together with arrays they build tables, and variant records hold one of several alternative sets of fields.

A record type

A record type lists its fields between RECORD and END, each with a type. A field of a record variable is selected with a dot and the field name.

book.mod
MODULE book;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  Book = RECORD
    title: ARRAY [0..31] OF CHAR;
    year: CARDINAL;
    edition: CARDINAL
  END;

VAR
  b: Book;

BEGIN
  b.title := "Programming in Modula-2";
  b.year := 1988;
  b.edition := 4;
  WriteString(b.title);
  WriteString(", ");
  WriteCard(b.year, 0);
  WriteString(", ");
  WriteString("edition ");
  WriteCard(b.edition, 0);
  WriteLn
END book.

Book has three fields: a character array and two cardinals. b.title, b.year and b.edition are used like ordinary variables of their types. Field names belong to the record, so another record type may use the same names.

$ gm2 book.mod -o book
$ ./book
Programming in Modula-2, 1988, edition 4

Assigning records

A record variable can be assigned to another of the same type. The assignment copies every field, and the two records stay independent.

copies.mod
MODULE copies;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

TYPE
  Point = RECORD
    x, y: INTEGER
  END;

VAR
  a, b: Point;

PROCEDURE WritePoint(p: Point);
BEGIN
  WriteString("(");
  WriteInt(p.x, 0);
  WriteString(", ");
  WriteInt(p.y, 0);
  WriteString(")")
END WritePoint;

BEGIN
  a.x := 3;
  a.y := -2;
  b := a;
  b.x := 10;
  WriteString("a = ");
  WritePoint(a);
  WriteString(", b = ");
  WritePoint(b);
  WriteLn
END copies.

After b := a, changing b.x leaves a as it was. Fields with the same type can share one declaration, as x, y: INTEGER does. WritePoint takes a whole record as a value parameter.

$ gm2 copies.mod -o copies
$ ./copies
a = (3, -2), b = (10, -2)

Comparing records

Like arrays, records can be assigned but not compared. The operators = and # reject record operands.

equality.mod
MODULE equality;

TYPE
  Point = RECORD
    x, y: INTEGER
  END;

VAR
  a, b: Point;

BEGIN
  a.x := 1;
  a.y := 2;
  b := a;
  IF a = b THEN
    a.x := 0
  END
END equality.

The compiler reports the comparison of a and b. Two records are compared field by field, in a function procedure written for the type.

$ gm2 equality.mod -o equality
equality.mod:15:8: error: inequality tests between composite types not allowed ‘a’ and ‘b’
   15 |   IF a = b THEN
      |      ~~^~~

The WITH statement

WITH r DO … END opens the fields of the record r, so they can be used without the prefix r. inside the statement.

with.mod
MODULE with;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  Account = RECORD
    owner: ARRAY [0..15] OF CHAR;
    number: CARDINAL;
    balance: CARDINAL;
    open: BOOLEAN
  END;

VAR
  acc: Account;

BEGIN
  WITH acc DO
    owner := "Lucia";
    number := 1024;
    balance := 250;
    open := TRUE
  END;

  WITH acc DO
    INC(balance, 100);
    WriteString(owner);
    WriteString(" #");
    WriteCard(number, 0);
    WriteString(": ");
    WriteCard(balance, 0);
    IF open THEN
      WriteString(" (open)")
    END;
    WriteLn
  END
END with.

The first WITH fills in the four fields of acc, the second changes and prints them. Inside WITH, balance means acc.balance. A field name hides a variable of the same name outside, so WITH blocks are best kept short.

$ gm2 with.mod -o with
$ ./with
Lucia #1024: 350 (open)

Records as parameters

A record is passed to a procedure like any other variable: as a value parameter it is copied, as a VAR parameter the procedure works on the caller's record. Wirth's original compilers allowed only simple types and pointers as function results; ISO Modula-2 and gm2 also allow records. This series returns records through a VAR parameter, which works with every compiler.

points.mod
MODULE points;

FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;
FROM MathLib0 IMPORT sqrt;

TYPE
  Point = RECORD
    x, y: REAL
  END;

VAR
  a, b, c: Point;

PROCEDURE SetPoint(VAR p: Point; x, y: REAL);
BEGIN
  p.x := x;
  p.y := y
END SetPoint;

PROCEDURE Distance(p, q: Point): REAL;
VAR
  dx, dy: REAL;
BEGIN
  dx := q.x - p.x;
  dy := q.y - p.y;
  RETURN sqrt(dx * dx + dy * dy)
END Distance;

PROCEDURE Middle(p, q: Point; VAR m: Point);
BEGIN
  m.x := (p.x + q.x) / 2.0;
  m.y := (p.y + q.y) / 2.0
END Middle;

BEGIN
  SetPoint(a, 0.0, 0.0);
  SetPoint(b, 3.0, 4.0);
  WriteString("distance:");
  WriteReal(Distance(a, b), 10);
  WriteLn;
  Middle(a, b, c);
  WriteString("middle:  ");
  WriteReal(c.x, 10);
  WriteReal(c.y, 10);
  WriteLn
END points.

SetPoint fills in a point through a VAR parameter. Distance reads two points and returns a REAL, and Middle returns a new point in its VAR parameter m. The distance from the origin to (3, 4) is 5.

$ gm2 points.mod -o points
$ ./points
distance:  5.000000
middle:    1.500000  2.000000

Nested records

A field may itself be a record. The fields of the inner record are reached through two dots, such as p.born.year.

nested.mod
MODULE nested;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  Date = RECORD
    day: [1..31];
    month: [1..12];
    year: CARDINAL
  END;
  Person = RECORD
    name: ARRAY [0..23] OF CHAR;
    born: Date
  END;

VAR
  p: Person;

PROCEDURE WriteDate(d: Date);
BEGIN
  WriteCard(d.day, 0);
  WriteString(".");
  WriteCard(d.month, 0);
  WriteString(".");
  WriteCard(d.year, 0)
END WriteDate;

PROCEDURE AgeIn(who: Person; year: CARDINAL): CARDINAL;
BEGIN
  RETURN year - who.born.year
END AgeIn;

BEGIN
  p.name := "Niklaus Wirth";
  p.born.day := 15;
  p.born.month := 2;
  p.born.year := 1934;

  WriteString(p.name);
  WriteString(", born ");
  WriteDate(p.born);
  WriteLn;
  WriteString("age when PIM was published: ");
  WriteCard(AgeIn(p, 1982), 0);
  WriteLn
END nested.

Person contains a Date. The fields of Date have subrange types, which document the valid values; gm2 15.2 does not range-check assignments to record fields, even with -fsoft-check-all, although it checks plain variables. WriteDate takes only the inner record, p.born, and AgeIn takes the whole person.

$ gm2 nested.mod -o nested
$ ./nested
Niklaus Wirth, born 15.2.1934
age when PIM was published: 48

Arrays of records

An array of records is a table: each element is a row, and each field a column. WITH works on an array element too.

stock.mod
MODULE stock;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Assign;

CONST
  Count = 4;

TYPE
  Item = RECORD
    name: ARRAY [0..15] OF CHAR;
    price: CARDINAL;
    quantity: CARDINAL
  END;

VAR
  items: ARRAY [1..Count] OF Item;
  i, total, low: CARDINAL;

PROCEDURE SetItem(VAR it: Item; name: ARRAY OF CHAR; price, quantity: CARDINAL);
BEGIN
  Assign(it.name, name);
  it.price := price;
  it.quantity := quantity
END SetItem;

BEGIN
  SetItem(items[1], "pencil", 120, 40);
  SetItem(items[2], "notebook", 350, 12);
  SetItem(items[3], "eraser", 80, 3);
  SetItem(items[4], "ruler", 210, 7);

  total := 0;
  low := 1;
  FOR i := 1 TO Count DO
    WITH items[i] DO
      WriteCard(quantity, 4);
      WriteString(" x ");
      WriteString(name);
      WriteLn;
      INC(total, price * quantity);
      IF quantity < items[low].quantity THEN
        low := i
      END
    END
  END;
  WriteString("stock value in cents: ");
  WriteCard(total, 0);
  WriteLn;
  WriteString("lowest stock: ");
  WriteString(items[low].name);
  WriteLn
END stock.

SetItem fills in one row and copies the name with Strings.Assign. The loop opens each row with WITH items[i], prints it, adds its value to the total and remembers the row with the lowest quantity. Prices are kept in cents, so the total is exact.

$ gm2 stock.mod -o stock
$ ./stock
  40 x pencil
  12 x notebook
   3 x eraser
   7 x ruler
stock value in cents: 10710
lowest stock: eraser

Variant records

A variant record has a CASE part whose fields depend on the value of a tag field. The variants share the same memory, so the record holds only one of them at a time.

shapes.mod
MODULE shapes;

FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;

CONST
  Pi = 3.14159265;

TYPE
  Kind = (Circle, Rectangle, Triangle);
  Shape = RECORD
    CASE kind: Kind OF
      Circle:
        radius: REAL |
      Rectangle:
        width, height: REAL |
      Triangle:
        base, altitude: REAL
    END
  END;

VAR
  s: ARRAY [1..3] OF Shape;
  i: CARDINAL;

PROCEDURE Area(sh: Shape): REAL;
BEGIN
  CASE sh.kind OF
    Circle: RETURN Pi * sh.radius * sh.radius |
    Rectangle: RETURN sh.width * sh.height |
    Triangle: RETURN sh.base * sh.altitude / 2.0
  END
END Area;

BEGIN
  s[1].kind := Circle;
  s[1].radius := 1.5;
  s[2].kind := Rectangle;
  s[2].width := 4.0;
  s[2].height := 2.5;
  s[3].kind := Triangle;
  s[3].base := 6.0;
  s[3].altitude := 3.0;

  FOR i := 1 TO 3 DO
    CASE s[i].kind OF
      Circle: WriteString("circle    ") |
      Rectangle: WriteString("rectangle ") |
      Triangle: WriteString("triangle  ")
    END;
    WriteReal(Area(s[i]), 10);
    WriteLn
  END
END shapes.

The tag field kind has the enumeration type Kind. A circle uses radius, a rectangle width and height, and a triangle base and altitude. Area selects the formula with a CASE statement on the tag. A program sets the tag first and then the fields of the matching variant.

$ gm2 shapes.mod -o shapes
$ ./shapes
circle      7.068583
rectangle  10.000000
triangle    9.000000

The tag is not checked

Nothing stops a program from reading a field of a variant other than the one the tag names. GNU Modula-2 does not check the tag, even with -fsoft-check-all.

unchecked.mod
MODULE unchecked;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  Kind = (Number, Letters);
  Value = RECORD
    CASE kind: Kind OF
      Number:
        n: CARDINAL |
      Letters:
        text: ARRAY [0..3] OF CHAR
    END
  END;

VAR
  v: Value;

BEGIN
  v.kind := Letters;
  v.text := "ABCD";
  WriteString("read as a number: ");
  WriteCard(v.n, 0);
  WriteLn;
  WriteString("size of a Value: ");
  WriteCard(SIZE(Value), 0);
  WriteLn
END unchecked.

The record holds four letters, but the program reads the field n of the other variant. The four bytes of "ABCD", codes 41H to 44H, are read as the cardinal 44434241H, which is 1145258561. The record is 8 bytes: 4 for the tag and 4 shared by the two variants. The checked build prints the same. Testing the tag before using a variant is the program's job.

$ gm2 unchecked.mod -o unchecked
$ ./unchecked
read as a number: 1145258561
size of a Value: 8
$ gm2 -fsoft-check-all unchecked.mod -o unchecked
$ ./unchecked
read as a number: 1145258561
size of a Value: 8

A grade report

The last program combines the parts of this article. Each student is a record with a name, an array of marks, a total and a result of an enumeration type.

grades.mod
MODULE grades;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Assign;

CONST
  Students = 4;
  Tests = 3;

TYPE
  Result = (Fail, Pass, Merit, Distinction);
  Student = RECORD
    name: ARRAY [0..15] OF CHAR;
    marks: ARRAY [1..Tests] OF CARDINAL;
    total: CARDINAL;
    result: Result
  END;

VAR
  class: ARRAY [1..Students] OF Student;
  i, best: CARDINAL;

PROCEDURE Enter(VAR st: Student; name: ARRAY OF CHAR; m1, m2, m3: CARDINAL);
BEGIN
  Assign(st.name, name);
  st.marks[1] := m1;
  st.marks[2] := m2;
  st.marks[3] := m3
END Enter;

PROCEDURE Evaluate(VAR st: Student);
VAR
  t: CARDINAL;
BEGIN
  WITH st DO
    total := 0;
    FOR t := 1 TO Tests DO
      INC(total, marks[t])
    END;
    CASE total DIV Tests OF
      0..49: result := Fail |
      50..69: result := Pass |
      70..84: result := Merit
    ELSE
      result := Distinction
    END
  END
END Evaluate;

BEGIN
  Enter(class[1], "Agnes", 72, 65, 80);
  Enter(class[2], "Boris", 45, 52, 38);
  Enter(class[3], "Clara", 91, 88, 95);
  Enter(class[4], "Dusan", 60, 71, 55);

  best := 1;
  FOR i := 1 TO Students DO
    Evaluate(class[i]);
    WITH class[i] DO
      WriteCard(total, 4);
      WriteString("  ");
      WriteString(name);
      CASE result OF
        Fail: WriteString(" - fail") |
        Pass: WriteString(" - pass") |
        Merit: WriteString(" - merit") |
        Distinction: WriteString(" - distinction")
      END;
      WriteLn;
      IF total > class[best].total THEN
        best := i
      END
    END
  END;
  WriteString("best result: ");
  WriteString(class[best].name);
  WriteLn
END grades.

Enter stores a name and three marks, and Evaluate computes the total and turns the average into a Result with a CASE on ranges. Both take the student as a VAR parameter, because they change it. The main loop prints each student and keeps the index of the best total.

$ gm2 grades.mod -o grades
$ ./grades
 217  Agnes - merit
 135  Boris - fail
 274  Clara - distinction
 186  Dusan - pass
best result: Clara

Next steps

The records of this article have a fixed number of elements, declared in arrays. The pointers article creates records at run time on the heap and links them with pointers.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared record types, assigned records, opened their fields with WITH, passed them to procedures, nested them, built tables from arrays of records and stored alternatives in variant records. The enumerations article covers the tag types, the arrays article the tables, and the strings article the Assign procedure used for the names.

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.