GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 42

Recursive function with shared static state

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

GATE 2007, Q42 2 marks · MCQ
Report issue

Scope, Lifetime & Storage Classes

Question 42, GATE 2007: What is f(5) for the following C function?
int f(int n) {
    static int r=0;
    if(n<=0) return 1;
    if(n>3) { r=n; return f(n-2)+2; }
    return f(n-1)+r;
}
Options:
(A) 5
(B) 7
(C) 9
(D) 18
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (11 steps)

1. Approach. The static r is one persistent shared object, not a fresh zero-initialized local for each recursive call. Record the single assignment r=5 before unwinding the recursion.

2. Derivation and interpretation. The static variable r is shared by all activations. In f(5), r becomes 5, and the return expression is f(3)+2. Calls f(3), f(2), and f(1) each recurse with n−1 and add the unchanged r=5. The base f(0)=1. Hence f(1)=6, f(2)=11, f(3)=16, and f(5)=18 (D). No smaller activation changes r, so operand evaluation order does not affect this particular call.

Original paper, page 10