MiP MiP - 3 years ago 350
Pascal Question

How does pass-by-reference work?

Pass-by-reference is easy to visualize with languages that use pointers mostly. But in Pascal, I can hardly see how the pointers pass around subroutines as arguments.

For example:

var a: array [0..2] of integer;
i : integer;

procedure swap(var x, y: integer);
var temp: integer;
temp := x;
x := y;
y := temp;

i := 0;
a[i] := 2;
swap(i, a[i]);

Can the
swap(i, a[i]);
procedural call statement be replaced with this equivalent pseudocode? Is this how interpreters work behind the scenes?

var tmpOldArrayExpression, tmpNewFirst, tmpNewSecond : integer;
tmpOldArrayExpression := i;
(tmpNewFst, tmpNewSnd) := swap(i, a[i]);
i := tmpNewFirst; { 2 }
a[tmpOldArrayEession] := tmpNewSecond; { 0 }

Answer Source

Behind the scenes, the function Swap is implemented as:

function Swap(x, y: ^integer); // or: PInteger
  temp: integer;
  temp := x^;
  x^ := y^;
  y^ := temp;

And it is in reality (but not syntactically) called like:

i := 0;
a[i] := 2;
swap(@i, @a[i]);

And Pascal is a compiled language. It is (generally) not interpreted.

To read more about this, read my article explaining pointers and references, especially about reference parameters. It is about Delphi, but the same principles apply to most Pascals.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download