In which of the following case(s) is it possible to obtain different results for call-by-reference and call-by-name parameter passing?
View worked solution
Answer: A;D
To understand when call-by-reference and call-by-name produce different results, let us look at how they handle parameter passing:
- Call-by-Reference: The address of the actual parameter is computed once at the time of the function call and passed to the formal parameter.
- Call-by-Name: The actual parameter is textually substituted into the function body. The expression is re-evaluated every time the formal parameter is accessed during execution.
Let's analyze the options:
-
Passing an expression as a parameter (Option A):
Suppose we pass an expression like as a parameter to a function, and the value of is modified inside the function.- In call-by-reference, is evaluated once before the call, stored in a temporary location, and its address is passed. Changes to inside the function do not affect this temporary value.
- In call-by-name, the expression is re-evaluated every time the parameter is accessed. If changes inside the function, the parameter's value changes accordingly.
-
Passing an array element as a parameter (Option D):
Suppose we pass an array element to a function, and the index variable is modified inside the function.- In call-by-reference, the address of is computed once at the start of the call. Even if changes inside the function, the parameter still points to the original array element.
- In call-by-name, the expression is substituted. If changes inside the function, subsequent accesses to the parameter will refer to the new element (this is known as Jensen's Device).
For simple arrays (Option B) or pointers (Option C), there are no dynamic index variables or expressions to re-evaluate, so both mechanisms yield the same behavior.
Free practice · Your answers on this page are not saved.
