This example program illustrates the basic mechanism of passing by reference.
The first thing to note is that this pseudocode does not contain any global variables. “i” is a local variable of the subroutine named “main”. Without a global variable, the subroutine “resetToZero” can initialize local variable “i” to zero.
On line 7, note that a by-directional arrow is used to link the local variable “i” of “main” to parameter “x” of “resetToZero”. This is because “x” becomes an alias of “i”. Whatever happens to “x” happens to “’i” immediately because they are two names of the same storage.
Here is the trace of this pseudocode.
trace | A | B | C | D | E | explanation |
1 | line# |
|
||||
2 | pre | There is no global variable. |
||||
3 | 9 | retline# | i | “i” is a local variable of “main”. |
||
4 | post | ? | A local variable does not have any specific value. |
|||
5 | 7 | retline# | x | The invocation of “resetToZero” also allocate two columns. |
||
6 | 8 | aka col C | Note that “x” is an alias of column C. This means that parameter “x” does not store a value, it is a mechanism to link to a column that does store a value. “aka” is used because “x” is an alias of column C. |
|||
7 | 3 | 0 | This is the essence of passing by reference. When “x” is updated to zero, column E itself is not updated. Instead, the column that “x” refers to, column C, is updated. Note that column C is not allocated by the invocation of “resetToZero”. |
|||
8 | 4 | retline# | x | The deallocation of “x” has no impact on what it refers to. |
||
9 | 8 | retline# | i |
|
||
10 | post |
|
||||