Output for pass-by-value and pass-by-name

158 views Asked by At

I am needing to find the result of the following code when x and y are passed-by-value and also when passed-by-name.

PROGRAM EX1; 
int i; //global
int A[3]; //global

    PROCEDURE P1(int x, int y)
    Begin
        y:=2; 
        PRINT(x); 
        i:=3; 
        PRINT(x); 
        i:=3; 
        PRINT(x); 
        PRINT(y); 
    End; 
BEGIN //main
    A[1]:=7; A[2]:=13; A[3]:=11; 
    i:=1; 
    P1(A[i],i); //first call
    P1(i,A[i]); //second call
END.

Here is what I concluded if x and y are pass by value: Outputs: 13, 11, 11, 3 Second Output: 1, 3, 3, 11. If that is wrong please help me understand why.

I am also not sure how pass-by-name would work in this code from the examples I have seen. Please help with that as well.

Assume static scoping.

1

There are 1 answers

0
FDavidov On

I will ignore during the description the fact that your code would most likely fail to compile/run, and will only address your specific question.

Regardless of the mechanism used to pass the parameters (by value or by name), the assignments to the variable i are meaningless: when passed by value, there is no meaning at all (within the function P1) the fact that the source parameters may be arrays; when passed by name and you pass A[i] where i=1, what reaches the body of function P1 is A[1] and hence changes to i would have no effect at all.

So, in both cases (by value and by name) you will get the same result, meaning: 7,7,7,2 for the first invocation, and 1,1,1,2 for the second.