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:
- The target is evaluated: the variable and, if any, its indices.
- The right-hand expression is evaluated, with the values that exist before assigning.
- 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
The program finishes normally.
1Starting point: a is 1 and b is 2.
2auxiliar <- a; copies the 1 into the auxiliary box.
3a <- b; overwrites the 1 in a with a 2. The 1 is still safe in auxiliar.
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.