Skip to content

SpecificationIII · Types and values

3.7

Records

A record groups several named pieces of data into a single value, like a card with its sections; assigning it copies it whole.

Markdown version

3.7.1 How to write it

Record «Name»
  Define «field» As «type»;
  …
EndRecord

3.7.2 How it works

A record is declared outside the algorithm, with a name and its fields. After that it is used like any other type: it is built by writing its name with one value per field, in the order they were declared, and each field is read or changed with a dot.

ProgramA student's card

Record Alumno
  Define nombre As String;
  Define nota As Real;
EndRecord
Algorithm Ficha
  Define ana As Alumno <- Alumno("Ana", 8.5);
  ana.nota <- ana.nota + 1;
  Write ana.nombre, ": ", ana.nota;
EndAlgorithm

Output

Ana: 9.5

The program finishes normally.

3.7.3 It is copied by value

A record is a value, not a reference. Assigning it, passing it to a subroutine or returning it copies all its fields. Changing the copy does not change the original.

ProgramEach variable has its own card

Record Casilla
  Define fila, columna As Integer;
EndRecord
Algorithm Tablero
  Define a As Casilla <- Casilla(1, 2);
  Define b As Casilla <- a;
  b.fila <- 10;
  Write a.fila, " ", b.fila, " ", a = b;
EndAlgorithm

Output

1 10 false

The program finishes normally.

Figure 3.7-1.Assigning a record makes a copy. Both cards start equal, but from then on they change separately.

Two cards, a and b, with the fields fila and columna. Both had fila 1 and columna 2; after changing b.fila to 10, only b shows 10 and a still has 1.

Two records of the same type are equal if all their fields are. A record cannot contain itself, directly or indirectly.

In short

  • A record groups named fields into a single value.
  • It is built with one value per field and accessed with a dot.
  • It is copied when assigned, passed or returned.
  • Two records are equal if all their fields are.