Consider a subroutine swap that takes two parameters and simply swaps their valu
ID: 3714015 • Letter: C
Question
Consider a subroutine swap that takes two parameters and simply swaps their values. For example, after calling swap(X,Y), X should have the original value of Y and Y the original value of X. Assume that variables to be swapped can be simple or subscripted (elements of an array), and they have the same type (integer). Show that it is impossible to write such a general-purpose swap subroutine in a language with:
Parameter passing by name. Hint: for the case of passing by name, consider mutually dependent parameters.
Explanation / Answer
answer
given by
Parameter passing by name:
procedure swap(x, y: int):
var t : int
t:=x;
x:=y;
y:=t;
end;
Main:
Declare i,a[];
Call swap(i,a)
By calling the subroutine by passed by name conflicts are taken care of between actual parameters and the local variables of the function.
Flow for the function call by its name:
temp:=i
i:=a
a=temp
Call by name does the wrong thing it can’t handle the swap properly by calling its name.
so it’s impossible to write code through call by name.