In which of the following cases is it possible to obtain different results for call-by-reference and call-by-name parameter passing methods?
View worked solution
Answer: C
To understand why the results differ, let us analyze how parameters are bound in both evaluation strategies:
- Call-by-Reference: The address of the actual parameter is evaluated once at the time of the function call. Inside the function, any access to the formal parameter directly uses this pre-computed address.
- Call-by-Name: The actual parameter expression is textually substituted for the formal parameter. It is re-evaluated every time the formal parameter is accessed or modified during execution.
Example Demonstration
Suppose we have a global index variable , an array , and a function foo(x):
int i = 1;
int A[5] = {10, 20, 30, 40, 50};
void foo(int x) {
i = 2;
x = 99;
}
foo(A[i]); // Passing an array element
1. Under Call-by-Reference:
- When
foo(A[i])is called, , so the address of is passed. - Inside
foo,iis updated to . - The assignment
x = 99writes directly to the reference of . - Result: becomes .
2. Under Call-by-Name:
- The formal parameter
xis textually replaced byA[i]. - Inside
foo, the body effectively becomes:i = 2; A[i] = 99; // x is replaced by A[i] - Since was updated to in the first step, the assignment
A[i] = 99evaluates toA[2] = 99. - Result: becomes , while remains unchanged.
Since the index variable of the array element can change inside the function, passing an array element (Option C) can yield different results under the two parameter-passing techniques.
Free practice · Your answers on this page are not saved.
