Consider the following program in some unidentified language which
supports procedures with parameters.
function joe(int a, int b, int c) begin a := b + c; b := c + 1; print a, b, c; end
function main begin int i := 5; int j := 10; ink k := 15; joe(i, j, j + k); print i, j, k; end
What values are printed by the program under each of the following
assumptions?
All parameters are passed by value.
35 26 25 5 10 15
Parameters are independent variables initialized to the values
of the argument expressions. Changes to them do not effect
the arguments.
Pass a and b by reference, and c by value.
35 26 25 35 26 15
This is very much the same, except the changes to a
and b are also made to i and j since
these parameters are aliases.
Pass a and b by value-result, and c by value.
35 26 25 35 26 15
This has the same effect as pass-by-reference, since the values
of a and b are returned to i and j
when the function returns.
All parameters are passed by name.
35 26 41 35 26 15
This is again similar to the last two, since changes to
a and b also change i and j.
The difference is the value of 41
printed for c, since
c is an alias for the expression j + k. The
assignment b := c + 1 changes b to 26, which changes
j, which changes j + k, now 26 + 15 = 41.
And now for something completely different.
function phil(int a, int b, int c) begin b := b + 5; b := a + c + 4; print a, b, c; end
function main begin int j := 10; ink k := 15; phil(j, j, j + k); print j, k; end
What values are printed by the program under each of the following
assumptions?
All parameters are passed by value.
10 39 25 10 15
Okay, so this one isn't all that different.
Pass a and b by reference, and c by value.
44 44 25 44 15
Here both a and b are aliases for j.
So the first assignment to b also changes a to
15. The second adds 29 more to b (as well as a and
j), making everyone 44.
Pass a and b by value-result, and c by value.
10 39 25 39 15
Here value-result differs from reference. To make this happens
usually requires sending the same parameter in two places, or
sending a global as a parameter. So it's either something a
professor makes up, or an unexpected accident that can be very
hard to figure out.
The first line is the same as pass-by-value
since the process begins the same way. While the function is
running, a and b are different values, so the
first assignment to b is completely destroyed by the
second one. Then the values are copied back. The second line
given here
depends on the assumption that the values are copied back in
left-to-right order so that the 10 is copied to j, then
the 39, so the later becomes the final value.
All parameters are passed by name.
49 49 64 49 15
This is like pass-by-reference, except now the first assignment
to b changes j, and hence
both a and c also, since a
is j, and c is j + k.
Thus the second assignment to b totals up
to 49, which becomes
the new value of a, b and j.
That also changes c, since it's still j + k, and
so prints out as 64.