Skip to content

SpecificationVI · Control flow

6.7

Leaving a loop

Exit ends the loop that contains it on the spot, even if its condition would still allow it to go on.

Markdown version

6.7.1 How to write it

Break;

6.7.2 How it works

Exit leaves the innermost loop that contains it and the program continues after its closing word. It is useful when searching: as soon as the thing appears, there is no need to keep looking.

ProgramFinding the first one that fits

Algorithm Buscar
  Dimension numeros[5] As Integer;
  For i <- 0 To 4 Do
    numeros[i] <- (i + 1) * 7;
  EndFor
  For Each n In numeros Do
    If n > 15 Then
      Write "Primero mayor que 15: ", n;
      Break;
    EndIf
    Write "Reviso ", n;
  EndFor
EndAlgorithm

Output

Reviso 7
Reviso 14
Primero mayor que 15: 21

The program finishes normally.

Figure 6.7-1.Exit cuts the loop on the third round. Cells 28 and 35 are never visited.

Five cells with 7, 14, 21, 28 and 35. 7, 14 and 21 are visited; at 21 a red line marks Exit and cells 28 and 35 are never visited.

If the loop has cleanups registered with [Defer](#control.diferir), they run on exit. There is no word for "skip to the next round".

In short

  • Exit ends the innermost loop.
  • It is only valid inside a loop.
  • It runs the pending cleanups of the loop.