Skip to content

SpecificationVI · Control flow

6.8

Cleanups with Defer

Defer notes down something to do when leaving the current block, whatever happens: closing a file, switching off a light, leaving things as they were.

Markdown version

6.8.1 How to write it

Defer
  «instrucciones»
EndDefer

6.8.2 How it works

When execution reaches Defer, the body does not run: it is pushed onto a stack. When leaving the block that holds the Defer —through the end, Exit, Return or a propagated error— the noted cleanups run, from the last to the first.

ProgramThe last thing opened is the first one closed

Algorithm Ordenado
  Write "abro la puerta";
  Defer
    Write "cierro la puerta";
  EndDefer
  Write "enciendo la luz";
  Defer
    Write "apago la luz";
  EndDefer
  Write "leo un rato";
EndAlgorithm

Output

abro la puerta
enciendo la luz
leo un rato
apago la luz
cierro la puerta

The program finishes normally.

  1. 1The first Defer is reached: "cierro la puerta" goes onto the stack.

  2. 2The second one is reached: "apago la luz" sits on top.

  3. 3When the block ends the top one comes off first, "apago la luz", and then "cierro la puerta".

Figure 6.8-1.Cleanups are stacked when reached and run in reverse when leaving the block.

A stack: first cierro la puerta goes in and apago la luz on top. On leaving, apago la luz runs first and then cierro la puerta.

Only what is reached counts: a Defer in a branch not taken notes nothing. Inside a loop, every round notes its own cleanups and runs them when that round ends:

ProgramCleanups per round

Algorithm Vueltas
  For i <- 1 To 3 Do
    Defer
      Write "fin de la vuelta ", i;
    EndDefer
    If i = 2 Then
      Break;
    EndIf
    Write "vuelta ", i;
  EndFor
EndAlgorithm

Output

vuelta 1
fin de la vuelta 1
fin de la vuelta 2

The program finishes normally.

In short

  • Defer notes a cleanup for when the block is left.
  • Cleanups run in the reverse of the order they were reached.
  • They run when leaving through the end, Exit, Return or a propagated error.
  • A trap ends the program without running them.