Discussion
What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is assumed?
a=3;
void n(x) {x = x * a; print(x);}
void m(y) {a = 1; a = y - a; n(a); print(a);}
void main() {m(a);}
Answer: D
The keyed output is 4, 4.
The pseudo-code has no declarations, so the key rests on reading the assignment a = 1 inside m as creating m's own local variable a (as an assignment does in many dynamically scoped languages). Under that reading:
- main calls m(a); y is a reference to the global a, which is 3.
- In m, a = 1 creates the local a; then a = y - a = 3 - 1 = 2.
- m calls n(a); x is a reference to m's local a. With dynamic scoping, the a inside n is the most recent active binding, m's local a, the same variable as x. So x = x * a = 2 * 2 = 4, and n prints 4.
- Back in m, print(a) prints the local a, now 4.
If every a were the single global variable, the output would be 0, 0 (a = 1, then a = y - a = 1 - 1 = 0), which is not offered; the options therefore assume the local reading. Under it, both prints show the same variable after n has changed it, which is why the two printed values are equal, ruling out 6, 2 and 4, 2.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development