Pass By Value & Reference

75 Views Asked by At

I have a practice question that has stumped me for an upcoming certification test. Please help anyway that you can! I think I understand how to get the pass-by-value portion of the answer, but NO IDEA on the pass-by-reference part of this question.

procedure calc ( pass-by-value int w,
                 pass-by-value int x,
                 pass-by-reference int y,
                 pass-by-reference z)

    w <-- w + 1
    x <-- x * 2
    y <-- y + 3
    z <-- z * 4

end procedure

What are the values of a and b at the end of the code fragment below?

int a <-- 5
int b <-- 6
calc (a, a, b, b)
2

There are 2 best solutions below

1
On BEST ANSWER

a is never changed outside the procedure because it's passed by value, while b will be changed, because it's passed by reference. Assignment to variables passed by reference will remain outside the procedure.

one way to look at it is to substitute reference arguments by the caller variable, substitute y,z by b. while no substitute for a because it's called by value.

now your code will exactly look like this if w,x passed by value y,z by reference: a will be 5 no change while b will be:

int a <-- 5
int b <-- 6
w <-- a + 1
x <-- a * 2
b <-- b + 3   => b will be 9 
b <-- b * 4   => b will be 36

b will be 36 inside the procedure and after return of the procedure.

1
On

Results:

w = 6, x = 10, y = 9, z = 36

After calculations a = 5 and b = 36