Question
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); }
Official answer and solution
- Official answer
- D
- From
- Official GATE 2016 answer key
Reference book mistakenly labels option C as correct despite deriving 4 and 4 in its steps.
Solution
Trace dynamic scope lookups along the active call stack with pass-by-reference aliases.
Under dynamic scoping, a non-local variable reference is resolved by searching back through the chain of active function calls (the call stack) until a declaration of that variable name is found. Pass-by-reference means formal parameters are bound directly to the memory location of the actual arguments.
Trace execution:
- Global declaration:
a = 3.
main()callsm(a):- In
m(y), formal parameteryis passed by reference toa(which is globala). - Inside
m(),a = 1;introduces/binds local variableainm's frame with value 1. - Next,
a = y - a;evaluates:yrefers to globala = 3, and locala = 1. Thus, localabecomes .
- In
m()callsn(a):- Formal parameter
xofnis passed by reference tom's local variablea. - Inside
n(x):x = x * a;
Under dynamic scoping, looking upain the caller's stack frame resolves tom's local variablea(value 2).
Sincexis also an alias form's locala, bothxandarefer to the same location!
Thus, , updatingm's localato 4. print(x);innprints 4.
- Formal parameter
- Control returns to
m():print(a);inmprintsm's locala, which now holds 4.
Both print calls output 4, yielding4, 4.
D
Assuming static (lexical) scoping where n would resolve a to global a = 3, which would yield and output 6, 2.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 1
- Question
- 46 of 65, printed as CS Q.36
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.