Skip to content

SpecificationVII · Subroutines

7.5

Returning a value with Return

Return ends the subprogram on the spot and, if it has a return type, hands the value to the caller.

Markdown version

7.5.1 How to write it

Return ⟦«expresión»⟧;

7.5.2 How it works

Return cuts everything: it leaves open loops and blocks and abandons the whole call. Whatever comes after does not run. That is why it is useful for leaving as soon as the answer is known:

ProgramLeaving as soon as you know

Subroutine PrimerNegativo(a As Integer, b As Integer, c As Integer) As Integer
  If a < 0 Then
    Return a;
  EndIf
  If b < 0 Then
    Return b;
  EndIf
  Return c;
EndSubroutine

Algorithm Principal
  Write PrimerNegativo(4, -2, -7);
EndAlgorithm

Output

-2

The program finishes normally.

Figure 7.5-1.Three possible exits. With 4, -2 and -7 the second one is taken, and the third is never reached.

Three Returns. The first If is false; the second holds and b, which is -2, is returned. The last Return is never reached.

Every path of a typed subprogram must end in a Return. If the engine finds none at all, it is an error before running. If there is one, but a particular path reaches the end without going through it, the failure is discovered when running that path.

In short

  • Return ends the call on the spot, also from inside loops.
  • It takes an expression if and only if the subprogram has a return type.
  • A path that reaches the end without returning fails when running.