Consider the following program in a language that has dynamic scooping:
var x: real;
procedure show:
begin print(x);end;
procedure small;
var x: real;
begin x: = 0.125; show; end;
begin x:=0.25
show; small
end.
Then the output of the program is:
View worked solution
Answer: C
In a programming language with dynamic scoping, a free variable in a procedure is resolved by searching the execution call stack (the dynamic chain) backward from the point of the call until a definition for that variable is found.
Let's trace the execution of the program step-by-step:
-
Global Initialization:
The global variable
xis declared. In the main block,xis assigned the value0.25.
Current active binding forx: . -
First Call (
show): The main block callsshow.- Inside
show, the variablexneeds to be printed. - Looking back at the call stack:
showmain. - The most recent active binding for
xis the globalx, which has the value0.25.
- Inside
-
Second Call (
small): The main block callssmall.- Inside
small, a local variablexis declared and assigned the value0.125. - Current active binding for
x: .
- Inside
-
Nested Call (
showfromsmall): Insidesmall, the procedureshowis called.- Inside
show, we look upx. - Looking back at the call stack:
showsmallmain. - The most recent active binding for
xin this chain is the local variablexinsidesmall, which has the value0.125.
- Inside
Therefore, the output of the program is 0.25 0.125, which corresponds to Option C.
Free practice · Your answers on this page are not saved.
