Skip to content

SpecificationVII · Subroutines

7.4

Calls

Calling a subprogram means pausing what you are doing, running the subprogram with its arguments and coming back exactly to where you paused.

Markdown version

7.4.1 How it works

A call writes the name and, inside required parentheses, the arguments. The arguments are computed from left to right and only once, and must match the parameters in number and type.

Every call creates a frame: a space of its own for its parameters and local variables. When it ends, the frame disappears and control goes back to the caller.

  1. 1Principal is running with its frame.

  2. 2Doble(21) pushes a new frame with n = 21. Principal waits.

  3. 3Doble returns 42: its frame disappears and Principal carries on with the value.

Figure 7.4-1.Frames are stacked when calling and removed when returning. Only the top one is running.

A stack with the Principal frame at the bottom. Calling Doble pushes a frame with n = 21; on return it disappears and the value 42 goes down to Principal.

A subprogram that returns a value is used as an expression, where a value is needed. One that returns nothing is used as a statement. Mixing them up has different consequences:

SituationResult
using as a value something that returns nothingerror
calling as a statement something that returns a valuewarning: the value is lost

ProgramA discarded value and one argument too many

Subroutine Doble(n As Integer) As Integer
  Return n * 2;
EndSubroutine

Algorithm Principal
  Doble(3);
  Write Doble(2, 3);
EndAlgorithm

Diagnostics

  • discardedReturnValue · warning · 6:3 · Return value from subroutine Doble is discarded
  • argumentCountMismatch · error · 7:9 · Incorrect number of arguments: expected 1 but found 2

The program finishes with an error.

In short

  • Parentheses are required; arguments are computed from left to right.
  • Number and types must match the signature.
  • Every call has its own frame, which disappears on return.
  • Discarding a returned value is a warning.