Skip to content

SpecificationIII · Types and values

3.8

Enumerations

An enumeration is a type with a closed list of named values, like the colours of a traffic light.

Markdown version

3.8.1 How to write it

Enum «Name»
  ⟦«member», «member», …⟧
EndEnum

3.8.2 How it works

An enumeration declares a new type whose only values are the members of the list. Each member is written with the type's name, a dot and its name. A variable of that type can only hold one of those members, so there are no invented values and no typos that go unnoticed.

ProgramA named traffic light

Enum Semaforo
  Rojo, Amarillo, Verde
EndEnum
Algorithm Cruce
  Define luz As Semaforo <- Semaforo.Verde;
  If luz = Semaforo.Verde Then
    Write "Cruzar con ", luz;
  EndIf
EndAlgorithm

Output

Cruzar con Verde

The program finishes normally.

Figure 3.8-1.An enumeration is a closed list. A variable of the type can only point to one of its members.

A box with the type Semaforo and its three members: Rojo, Amarillo and Verde. A variable luz, outside the box, points to the member Verde.

Enumerations go very well with Switch, which can have one case per member:

ProgramOne case per colour

Enum Semaforo
  Rojo, Amarillo, Verde
EndEnum
Algorithm Indicacion
  Define luz As Semaforo <- Semaforo.Amarillo;
  Switch luz Do
    Semaforo.Rojo: Write "Para";
    Semaforo.Amarillo: Write "Precaución";
    Semaforo.Verde: Write "Adelante";
  EndSwitch
EndAlgorithm

Output

Precaución

The program finishes normally.

In short

  • An enumeration is a type with a closed list of members.
  • Members are written Type.member.
  • They only accept equality and inequality.
  • They work very well with Switch.