Skip to content

SpecificationV · Declarations and statements

5.3

Assignment

x <- value stores a new value in a variable and forgets the one it had.

Markdown version

5.3.1 How to write it

«destino» <- «expresión»;

5.3.2 How it works

Assignment happens in three stages, always in this order:

  1. The target is evaluated: the variable and, if any, its indices.
  2. The right-hand expression is evaluated, with the values that exist before assigning.
  3. The result is stored in the target.

That is why contador <- contador + 1 works: the right side reads the old value and the result replaces the old one.

The classic example is swapping two values. A third variable is needed, because assigning loses what was there:

ProgramSwapping two variables

Algorithm Intercambio
  Define a As Integer <- 1;
  Define b As Integer <- 2;
  Define auxiliar As Integer;
  auxiliar <- a;
  a <- b;
  b <- auxiliar;
  Write a, " ", b;
EndAlgorithm

Output

2 1

The program finishes normally.

  1. 1Starting point: a is 1 and b is 2.

  2. 2auxiliar <- a; copies the 1 into the auxiliary box.

  3. 3a <- b; overwrites the 1 in a with a 2. The 1 is still safe in auxiliar.

  4. 4b <- auxiliar; gets the 1 back. The values are swapped.

Figure 5.3-1.Swapping two values needs an auxiliary box that keeps the first one before it is overwritten.

Three boxes a, b and auxiliar. a is 1 and b is 2. First auxiliar receives 1, then a receives 2 and finally b receives 1 from auxiliar.

Assigning an object copies the reference, not the object: afterwards both variables name the same object. A whole array is not assigned in one go.

In short

  • <- stores a new value and forgets the previous one.
  • First the target, then the right side, finally the store.
  • The type must fit; indices are checked when running.