GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 31

Recursion with a persistent static counter

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2004 paper

GATE 2004, Q31 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 31, GATE 2004: For the first invocation of this C function, what does f(1) return?
int f(int n) {
  static int i=1;
  if(n>=5) return n;
  n=n+i; i++;
  return f(n);
}
Options:
(A) 5
(B) 6
(C) 7
(D) 8
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step through it (6 steps)

1. On the first call, n=1,i=1; the update yields n=2,i=2. The next call yields n=4,i=3, then n=7,i=4.

2. Since7≥5, that call returns7 and the result propagates back, C. This assumes f(1) is the first call, since static i persists across calls.

3. Teaching check: Static storage is initialized once, not once per recursive activation. The entry states (n,i) are (1,1),(2,2),(4,3),(7,4). Replacing static i with an ordinary local initialized to 1 would produce a different trace and return 5.

Original paper, page 4