6.2.1 How to write it
Switch «selector» Do
«etiqueta», «etiqueta»:
«instrucciones»
⟦Otherwise:
«instrucciones»⟧
EndSwitch6.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
EndAlgorithmOutput
Fin de semana
The program finishes normally.
1The selector is computed only once:
diais 6.26 is in the second branch: its
Writeruns.3When the branch ends the
Switchis left, without going through the others.
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
EndAlgorithmDiagnostics
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
Switchcomputes the selector once and runs a single branch.- Labels: integers or enumeration members, never repeated.
- No fall-through between branches;
Otherwiseis optional. - With enumerations, the branches must cover every member.