Skip to content
Official PYQ · 2003

GATE CS 2003 Q73 — Programming in C

Explain with AI

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:

Choose one option
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 + j is passed from main(), the variables i and j refer to the global variables (i = 100, j = 5), because there are no local declarations of i or j in main().
  • 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:

  1. main() calls P(i + j). The actual parameter expression is i + j.
  2. Inside P(x):
    • int i = 10; declares a local variable i and initializes it to 10.
    • print(x + 10); is executed. This is the first time the formal parameter x is referenced:
      • The expression i + j is evaluated in the environment of the caller (main) using static scoping.
      • Global i = 100 and global j = 5.
      • Thus, x evaluates to 100+5=105100 + 5 = 105.
      • This value 105 is cached for x.
      • The statement prints 105+10=115105 + 10 = 115.
    • i = 200; updates the local variable i to 200.
    • j = 20; updates the global variable j to 20.
    • print(x); is executed:
      • Since the parameter passing mechanism is call by need, the cached value of x (which is 105) is reused directly without re-evaluating the expression.
      • The statement prints 105.

Therefore, the values printed by the program are 115,105115, 105.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions