Using (Dynamic scoping)
procedure Main is
X, Y, Z : Integer;
procedure Suba is
A, Y, X : Integer;
begin
-- Suba body
end;
procedure Subb is
A, B, Z : Integer;
begin
-- Subb body
end;
procedure Subc
A, X, W : Integer;
begin
--- Subc body
end;
begin
--- Main body
end;
The question is: For the calling sequence, state which variables are visible during the execution of the last procedure Main calls Suba; Suba calls Subb; Subb calls Subc
Why is the answer: Suba: A, X, W Subb: B, Z Subc: Y
I tried working through it and I just don't see how that is the answer can anyone provide an explanation
Each call "inherits" the variables visible by its caller, and introduces its own variables. If a call introduces a variable with the same name as one in the caller, the caller's variable is shadowed. Picture the layers like this, as visible from inside Subc
:
Main X Y Z
Suba A Y Z
Subb A B Z
Subc A W X
The variables you can see are the first ones in each column looking up from the bottom. This would suggest that from inside the call to Subc
, you can see the following:
* `A`, `W`, and `X` as defined by `Subc`.
* `B` and `Z` as defined by `Subb`.
* `Y` as defined by `Suba`.
This reverses the rolls of Suba
and Subc
as you mention in the question. That answer doesn't really make sense, because Suba
doesn't define W
at all.