Study the following program written in a block-structured language:
Var x, y:interger;
procedure P(n:interger);
begin
x:=(n+2)/(n-3);
end;
procedure Q
Var x, y:interger;
begin
x:=3;
y:=4;
P(y);
Write(x) __(1)
end;
begin
x:=7;
y:=8;
Q;
Write(x); __(2)
end.
What will be printed by the write statements marked and in the program if the variables are statically scoped?
View worked solution
Answer: A
Under static (lexical) scoping, a variable reference is resolved in the block in which the procedure is defined, rather than where it is called.
Let's trace the execution step-by-step:
- Main Program Execution:
- The global variables are initialized: and .
- Procedure is called.
- Inside Procedure :
- declares its own local variables and .
- Local and local .
- calls with the argument .
- Inside Procedure :
- is defined at the global level, so any non-local variable reference in resolves to the global scope.
- The assignment is: .
- With , we get: .
- Returning to :
- The statement
Write(x)at (1) refers to 's local variable , which is still . Thus, is printed.
- The statement
- Returning to Main Program:
- The statement
Write(x)at (2) refers to the global variable , which was updated to by procedure . Thus, is printed.
- The statement
Therefore, the values printed are .
Free practice · Your answers on this page are not saved.
