|
Passing by reference means that the subroutine actually refers to the passed variable rather than its value. Any changes to the value will affect the caller variable. We declare a variable to be passed by reference with the var prefix. Rewriting the above code to use by reference changes matters:
|
|
|
procedure DoIt(Var A : Integer);
begin
A := A * 2;
ShowMessageFmt('A in the procedure = %d',[A]);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
A : Integer;
begin
A := 22;
ShowMessageFmt('A in program before call = %d',[A]);
// Call the procedure
DoIt(A);
ShowMessageFmt('A in program now = %d',[A]);
end;
|
|
|
A in program before call = 22
A in the procedure = 44
A in program now = 44
|
|
|
Now the caller A variable is updated by the procedure.
|
|
|
This is a very useful way of returning data from a procedure, as used by, for example, the Delphi Insert routine. It also allows us to return more than one value from a subroutine.
|