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);}
If the programming language uses static scoping and call by need parameter passing mechanism, the values printed by the above program are:
View worked solution
Answer: D
To determine the output of the program, we need to understand how static scoping and call by need parameter passing work:
- Static Scoping: The binding of variable names to their values is determined by their location in the source code. When the actual parameter expression
i + jis passed frommain(), the variablesiandjrefer to the global variables (i = 100,j = 5), because there are no local declarations ofiorjinmain(). - Call by Need: This is a lazy evaluation strategy (memoized version of call-by-name). The actual parameter expression is evaluated only the first time its value is needed. Once evaluated, the result is cached, and any subsequent references to the formal parameter use this cached value.
Step-by-Step Execution:
-
main()callsP(i + j). The actual parameter expression isi + j. -
Inside
P(x):int i = 10;declares a local variableiand initializes it to10.-
print(x + 10);is executed. This is the first time the formal parameterxis referenced:- The expression
i + jis evaluated in the environment of the caller (main) using static scoping. - Global
i = 100and globalj = 5. - Thus,
xevaluates to . - This value
105is cached forx. - The statement prints .
- The expression
i = 200;updates the local variableito200.j = 20;updates the global variablejto20.-
print(x);is executed:- Since the parameter passing mechanism is call by need, the cached value of
x(which is105) is reused directly without re-evaluating the expression. - The statement prints
105.
- Since the parameter passing mechanism is call by need, the cached value of
Therefore, the values printed by the program are .
Free practice · Your answers on this page are not saved.
