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;
EndAlgorithmOutput
5 6
The program finishes normally.
1
Copia(x)creates a new boxnwith a copied 5. Changing it leavesxas it was.2
Incrementar(x)creates no box:npoints to the box ofx, and adding 1 changesx.
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.
| Mark | What the subprogram receives |
|---|---|
none or By Value | a copy of the value |
By Reference | the 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 Referenceshares the caller's variable.- Arrays always go by reference.