Reputation: 1
I am learning parameter passing.
I've been working on a question about parameter passing, but I don't understand one problem.
I searched the Internet, but there was no example of a parameter being expression.
If it's a expression, can I know how to evaluate pass-by-name?
The problem is as follows.
function func(int a, int b, int c)
begin
a := b + c;
b := c + 1;
print a, b, c;
end
function main
begin
int x := 10;
int y := 5;
ink z := 15;
func(x, y, y + z);
print x, y, z;
end
Upvotes: 0
Views: 45
Reputation: 51132
From Wikipedia: (note that "call by name" and "pass by name" mean the same thing.)
Call by name is an evaluation strategy where the arguments to a function are not evaluated before the function is called—rather, they are substituted directly into the function body (using capture-avoiding substitution) and then left to be evaluated whenever they appear in the function. If an argument is not used in the function body, the argument is never evaluated; if it is used several times, it is re-evaluated each time it appears.
So for your function, we should make the substitutions a → x
, b → y
and c → y + z
accordingly:
begin
x := y + (y + z);
y := (y + z) + 1;
print x, y, (y + z);
end
I've put brackets around the places where c
is substituted, to make clear that when the expression is "copy/pasted" into the function, it doesn't change the precedence of the other operations; for example, 3 * c
would be equivalent to 3 * (x + y)
, not 3 * x + y
.
The fact that c
is replaced by the expression y + z
rather than a simple variable, doesn't create any problems here, because c
never appeared on the left side of an assignment statement.
Upvotes: 0