int f(int n) { static int s = 0; s += n; return n ? f(n - 1) : s; } What does f(4) return?
Correct answer
D. 10
14 views
D. 10
14 views
Static local in recursion is shared by every frame, so s accumulates 4 + 3 + 2 + 1 = 10 during the descent and the base case returns that single object. Every unwinding frame also returns 10, because they all read the same storage. Making s automatic would give 0, since each frame would add n to its own copy and the base case would return its own zero.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.