Understanding call by value-result and call by reference differnce

437 Views Asked by At

So I have this piece of Pascal code:

program P;

var a: array [1..2] of Integer;
var i :Integer;
var k :Integer;

procedure update(x,y,z: Integer);
    begin
        x := x+1;
        y := x*2;
        x := y;    
        k := x;
     end


begin
     a[1] := 5; a[2] := 10;
     k := 3;
     for i:=1 to 2 do
       begin
          update(a[i],a[2],k);
          print(a);
          print(k)
       end
end.

(assume that 'print' prints elements of array separated by spaces, and then prints a new line and also for an integer it just prints it)

And i'm trying to understand how different the output would be if the function call was by value-result or by reference.

obviously, if it was just by-value, it's easy to tell that the procedure wouldn't make any difference to the actual parameter, i.e the output (in by value) should be: 5 10 3 5 10 3.

I think that if it was be value-result it would have been, at least the first iteration: 12 12 12. at the case of by reference I got confused. What would it be?

1

There are 1 best solutions below

0
On BEST ANSWER

You haven't declared any variable parameters. The variable K will be changed, but that doesn't count in this context and is generally considered bad practice.

PROGRAM ParamTest;

VAR
   A, B : Integer;

PROCEDURE TestProc(X : Integer; VAR Y : Integer; CONST Z : Integer);

BEGIN
   X := X + Z;
   Y := Y + Z;
END;

BEGIN
   A := 10;
   B := 10;
   TestProc(A, B, 5);
   WriteLn(A, ' ', B);
END.
  • X : Call by value
  • Y : Call by reference
  • Z : Call by constant

The output of this program should be 10 15.

With declaring Zas constant parameter you promise to the compiler that you don't change that value. The following procedure variant should give an error while compiling.

PROCEDURE TestProc(X : Integer; VAR Y : Integer; CONST Z : Integer);

BEGIN
   X := X + Z;
   Y := Y + Z;
   Z := Z + 1;
END;