Skip to content

SpecificationVI · Control flow

6.2

Multiple selection with Switch

Switch looks at a value only once and jumps straight to the branch whose label matches.

Markdown version

6.2.1 How to write it

Switch «selector» Do
  «etiqueta», «etiqueta»:
    «instrucciones»
  ⟦Otherwise:
    «instrucciones»⟧
EndSwitch

6.2.2 How it works

The selector is computed once. Then the branch with that label is found, run, and the selection ends: there is no "fall-through" to the next branch. If none matches and there is no Otherwise, nothing is done.

ProgramIs there school today?

Algorithm DiaSemana
  Define dia As Integer <- 6;
  Switch dia Do
    1, 2, 3, 4, 5:
      Write "Hay clase";
    6, 7:
      Write "Fin de semana";
    Otherwise:
      Write "Ese día no existe";
  EndSwitch
EndAlgorithm

Output

Fin de semana

The program finishes normally.

  1. 1The selector is computed only once: dia is 6.

  2. 26 is in the second branch: its Write runs.

  3. 3When the branch ends the Switch is left, without going through the others.

Figure 6.2-1.The selector is 6, so the engine jumps to the branch holding that label. The others are not even looked at.

A Switch on dia with three branches: 1 to 5 school day, 6 and 7 weekend, and Otherwise. The selector is 6 and only the second branch is followed down to EndSwitch.

Labels are integer literals (signed if needed) or members of an enumeration. Reals, characters, texts and booleans are not valid selectors. A label cannot be repeated.

6.2.3 With enumerations

If the selector is an enumeration, the branches must cover all its members, or include Otherwise. That way the engine warns you when a new member is added and nobody handles it.

ProgramAn incomplete traffic light

Enum Semaforo
  Rojo, Ambar, Verde
EndEnum
Algorithm Cruce
  Define luz As Semaforo <- Semaforo.Ambar;
  Switch luz Do
    Semaforo.Rojo:
      Write "Para";
    Semaforo.Verde:
      Write "Pasa";
  EndSwitch
EndAlgorithm

Diagnostics

  • nonExhaustiveSwitch · error · 6:3 · Missing branches: Semaforo.Ambar

The program finishes with an error.

The message names the missing members, in the order they were declared. Switch also opens variants such as Optional and Result: that is explained in Optional and Result.

In short

  • Switch computes the selector once and runs a single branch.
  • Labels: integers or enumeration members, never repeated.
  • No fall-through between branches; Otherwise is optional.
  • With enumerations, the branches must cover every member.