Skip to content

SpecificationVII · Subroutines

7.2

Parameters

Parameters are the input variables of a subprogram: on every call they receive a copy of the values passed to it.

Markdown version

7.2.1 How it works

Every parameter has a name and a required type. In the call, the arguments are assigned to the parameters in order. Without any mark, passing is by value: the parameter is a new variable with a copy of the argument, and changing it does not affect the caller.

ProgramThe parameter is a copy

Subroutine Incrementar(n As Integer By Reference)
  n <- n + 1;
EndSubroutine

Subroutine Copia(n As Integer)
  n <- n + 1;
EndSubroutine

Algorithm Principal
  Define x As Integer <- 5;
  Copia(x);
  Write x;
  Incrementar(x);
  Write x;
EndAlgorithm

Output

5
6

The program finishes normally.

  1. 1Copia(x) creates a new box n with a copied 5. Changing it leaves x as it was.

  2. 2Incrementar(x) creates no box: n points to the box of x, and adding 1 changes x.

Figure 7.2-1.By value, the subprogram gets its own box with a copy. By reference, its parameter is another name for the caller's box.

On the left, the main frame with x equal to 5. In the first step, Copia receives a box n with a copy that becomes 6 without changing x. In the second, Incrementar receives an arrow to x, which becomes 6.

MarkWhat the subprogram receives
none or By Valuea copy of the value
By Referencethe variable itself

The mark goes after the type and only affects that parameter. Arrays are always passed by reference: marking them By Value is an error.

In short

  • Every parameter has a name and a type.
  • By default a copy is passed: changing it does not affect the outside.
  • By Reference shares the caller's variable.
  • Arrays always go by reference.