GATE | GATE-CS-2003 | Question 73

The following program fragment is written in a programming language that allows 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;
    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

(A) 115, 220
(B) 25, 220
(C) 25, 15
(D) 115, 105

Answer: (D)

Explanation: Background :
Call-by-need is a declarative and functional language paradigm. As opposed to call-by-value, it only evaluates the argument given to a function when it is need, and caches it for further use. Call-by-name is a bit different from call-by-need in the sense that it evaluates in the lazy fashion only but doesn’t cache the calculated value. Hence, call-by-need requires to evaluate once if the argument is being used, call-by-value needs to evaluate it no matter if the argument is used or not, and call-by-name evaluates the same argument multiple times as and when it is used.

Explanation :

Value of variable x doesn’t change anytime in the function P(x). Hence, whatever its value is when this function is called, only that will be used in all the print statements. Clearly, 100+5+10, 100+5 i.e. 115, 105 will be printed by the program.

This solution is contributed by vineet purswani

Another Solution:

Here in main function P(i+j) function is called with arguments values i =100 and j = 5(since static scoping).Now when P(100+5) is called, here in P function, j is a free variable and i is a local variable.Now take a look at the steps in P function :

step_1: Local variable i is intialized to value 0.

step_2: Here value of x+10 is printed and since it’s call by need,so value of x is calculated to 105 and it’s stored in cache for further use.Also 115 is printed here.

step_3: Now, i is assigned value 200.

step_4: Here, j is a free variable, So it’s scope is searched in immediate outer block until we find variable j’s declaration.Global variable j’s value is changed from 5 to 20.

step_5: x value is printed as 105.Since it’s uses the cache stored value of x.

The output would be similar to C programming language as C does static scoping only.

This solution is contributed by Nirmal Bharadwaj

Quiz of this Question

My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.