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); }View worked solution
Answer: D
To find the output, we trace the execution step-by-step under pass-by-reference and dynamic scoping:
- Initial State: Global variable .
- Execution of
main():- Calls
m(a). Since parameters are passed by reference, the formal parameteryinmbecomes an alias for the global variablea(value ).
- Calls
- Execution of
m(y):a = 1;: Under dynamic scoping, this assignment implicitly creates/binds a local variableain the scope ofmwith an initial value of .a = y - a;: Updatesm's localato .n(a);: Callsnpassingm's localaby reference. Thus, the formal parameterxinnbecomes an alias form's locala.
- Execution of
n(x):x = x * a;: Under dynamic scoping, the variableais resolved by searching up the active call stack (nm). It resolves tom's local variablea(value ).- Since
xis a reference tom's locala, this statement evaluates to: print(x);prints .
- Return to
m(y):print(a);prints the current value ofm's locala, which is now .
Thus, the printed output is .
Free practice · Your answers on this page are not saved.
