Consider the following code written in a pass-by-reference language like FORTRAN and these statements about the code.
subroutine swap(ix,iy)
it = ix
L1 : ix = iy
L2 : iy = it
end
ia = 3
ib = 8
call swap (ia, ib+5)
print *, ia, ib
end
S1: The compiler will generate code to allocate a temporary nameless cell, initialize it to 13, and pass the address of the cell to swap
S2: On execution the code will generate a runtime error on line L1
S3: On execution the code will generate a runtime error on line L2
S4: The program will print 13 and 8
S5: The program will print 13 and -2
Exactly the following set of statement(s) is correct:
View worked solution
Answer: B
To understand the behavior of the code, let's analyze how pass-by-reference handles different types of arguments (variables vs. expressions):
1. Handling of Arguments in Pass-by-Reference
- Variables (L-values): When a variable like
iais passed, its actual memory address is passed to the subroutine. Any modification to the corresponding parameter inside the subroutine directly affects the original variable. - Expressions/Constants (R-values): When an expression like
ib + 5is passed, it does not have a persistent memory address. To handle this, the compiler allocates a temporary nameless memory cell, evaluates the expression (which is ), stores this value in the temporary cell, and passes the address of this temporary cell to the subroutine. This validates statement S1.
2. Step-by-Step Execution Trace
Initially, we have:
ia = 3ib = 8
When call swap(ia, ib + 5) is executed:
- A temporary cell (let's call it
temp) is created with value13. - The address of
iais bound to parameterix. - The address of
tempis bound to parameteriy.
Inside the subroutine swap(ix, iy):
it = ix: The local variableitgets the value ofix(which isia, i.e., ). So,it = 3.L1: ix = iy: The variableix(which isia) is assigned the value ofiy(which istemp, i.e., ). Thus,iabecomes .L2: iy = it: The variableiy(which istemp) is assigned the value ofit(which is ). Thus,tempbecomes .
3. Final Output
After returning from the subroutine:
iahas been updated to .ibremains unchanged at (since only the expressionib + 5was passed using a temporary cell, notibitself).
Thus, the print statement print *, ia, ib outputs 13 and 8. This validates statement S4.
Therefore, the correct statements are S1 and S4, which corresponds to option B.
Free practice · Your answers on this page are not saved.
