Question

Consider the C function given below:

int f(int j)
{
    static int i = 50;
    int k;
    if (i == j)
    {
        printf("something");
        k = f(i);
        return 0;
    }
    else return 0;
}

Which one of the following is TRUE?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2014 answer key

Solution

Trace the control flow and state of the static variable i when the function is invoked with j = 50.

  1. Static Variable Semantics in C:

    • static int i = 50; is initialized once at program startup and retains its value across recursive calls.
    • Inside f(int j), i is not modified by any assignment.
  2. Execution with j=50j = 50:

    • On initial call f(50):
      • The condition if (i == j) evaluates 50==5050 == 50, which is TRUE.
      • The string "something" is printed.
      • The recursive call k = f(i); is issued with argument i=50i = 50.
    • On the recursive call f(50):
      • Parameter j=50j = 50.
      • Static variable ii remains 5050.
      • i == j is again TRUE, prints "something", and calls f(50) again.
  3. Resulting Behavior:

    • Each recursive call creates a new stack frame on the call stack.
    • Because the recursion has no terminating condition when j=50j = 50, it recurses infinitely until memory allocated for the call stack is exhausted, triggering a stack overflow crash.
    • Therefore, the function will exhaust the runtime stack or run into an infinite loop when j=50j = 50 (Option D).
Final answer

D

Common trap

Assuming that return 0 is reached; the return statement is placed after the recursive call k = f(i), which never returns.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 2
Question
52 of 65, printed as CS Q.42
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.