# 7.3 Parameters by reference

> A `By Reference` parameter is another name for the caller's variable: whatever the subprogram does to it, it does to that variable.

Web page: https://pseudolearn.app/en/spec/subprogramas/referencia

> **In one sentence**
>
> A `By Reference` parameter is another name for the caller's variable: whatever the subprogram does to it, it does to that variable.

## 7.3.1 How it works

Since the subprogram receives a variable and not a value, the argument must be a [designator](https://pseudolearn.app/en/spec/declaraciones/designadores.md) of the **exact type**: a variable, a cell or an attribute. A literal or an operation will not do.

The typical use is returning **more than one result**:

### Program: Two results by reference

```pseudolearn
Subroutine Dividir(a As Integer, b As Integer, cociente As Integer By Reference, resto As Integer By Reference)
  cociente <- a Div b;
  resto <- a Mod b;
EndSubroutine

Algorithm Principal
  Define c, r As Integer;
  Dividir(17, 5, c, r);
  Write c, " ", r;
EndAlgorithm
```

**Output**

```text
3 2
```

*The program finishes normally.*

**Figure 7.3-1: Output parameters**

On the left, the main boxes c and r with 3 and 2. On the right, Dividir with cociente and resto, which are arrows to c and r.

`cociente` and `resto` have no box of their own: they are arrows to `c` and `r`. Assigning to them fills the caller's boxes.

`c` and `r` had no value before the call, and that is not an error: the engine sees that `Dividir` gives them a value **before reading them** on every path. Those parameters are **output** parameters. If the subprogram read the parameter before assigning it, the argument would have to arrive with a value.

> **Limit**
>
> - The index of a cell passed by reference is computed only once, at the call. An invalid index fails before entering the subprogram.
> - Two parameters may refer to the same variable; it is not forbidden.
> - In recursive subprograms no parameter counts as an output parameter.

> **Common mistakes**
>
> ### Program: A literal by reference
>
> ```pseudolearn
> Subroutine Incrementar(n As Integer By Reference)
>   n <- n + 1;
> EndSubroutine
>
> Algorithm Principal
>   Incrementar(5);
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `byReferenceArgumentRequiresDesignator` (error, 6:3): An argument passed by reference must be a variable or array element
>
> *The program finishes with an error.*

**In short**
- `By Reference` shares the caller's variable.
- The argument must be a designator of the exact type.
- It is used to return several results.
- If the subprogram assigns before reading, the argument may arrive without a value.

**See also**
- [7.2 Parameters](https://pseudolearn.app/en/spec/subprogramas/parametros.md)
- [5.4 Designators](https://pseudolearn.app/en/spec/declaraciones/designadores.md)
- [5.5 Variables without a value](https://pseudolearn.app/en/spec/declaraciones/sin-valor.md)
