MiP
MiP

Reputation: 6442

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;
    begin
       temp := x;
       x := y;
       y := temp;
    end;

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

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 }

Upvotes: 0

Views: 397

Answers (2)

Marco van de Voort
Marco van de Voort

Reputation: 26361

Afaik Pascal is even simpler than C in this regard, because while yes it has separate syntax, but there are no rules about parameters being aliases of each other (which IIRC C does have)

Upvotes: 0

Rudy Velthuis
Rudy Velthuis

Reputation: 28836

Behind the scenes, the function Swap is implemented as:

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

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.

Upvotes: 1

Related Questions