I am stuck at the following problem on static/dynamic scoping:
The following program fragment is written in a programming language that allows global variables and does not allow nested declarations of functions.
global int i = 100, j = 5;
void P(x) {
int i = 10;
print(x + 10);
i = 200;
j = 20;
print (x);
}
main() {P(i + j);}
Q1. If the programming language uses static scoping and call by need parameter passing mechanism, the values printed by the above program are
(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105
Q2. If the programming language uses dynamic scoping and call by name parameter passing mechanism, the values printed by the above program are
(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105
What I think:
On Q1: As it's static scoping and as per call by need, x should be replaced with i + j. But it will cause a local name conflict as there is already a variable with name i. So it (the global i) might be renamed, lets say to i1, and then call will be:
first call: print(x+10) -> (i1 + j + 10) -> (100 + 5 + 10) -> 115
second call: print(x) -> print(i1 + j) -> 105 (Already evaluated - call by need)
On Q2: In dynamic scoping, you search for a variable in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack.
As per call by name:
print (i1 + j + 10) -> print (100 + 5 +10 ) -> 115
And the second call will be
print(x) -> print(i1 + j) -> (100 + 20) = 120 // Evaluate again - Call be name.
Is this answer correct? (Not present in the options) Is there something I'm missing? (Dynamic binding may be?)