1. Home
  2. Computer Science MCQs
  3. C Programming
  4. int f(int n) { static int s = 0; s += n; return n ? f(n…

Added 30 Nov -0001

int f(int n) { static int s = 0; s += n; return n ? f(n - 1) : s; } What does f(4) return?

  1. 4
  2. 0
  3. 24
  4. 10 Correct answer

Correct answer

D. 10

14 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs