ProgrammingHardWipro · Cognizant pattern

What is printed? (Assume no overflow trapping.)

What is printed? (Assume no overflow trapping.)
int f(int n) {
    if (n == 0) return 0;
    return n + f(n - 1);
}
int main(void) {
    printf("%d", f(100000));
}
  1. A. Compilation error: recursion depth must be a compile-time constant
  2. B. It prints the correctly computed sum 5000050000
  3. C. Stack overflow / undefined behaviour / crash, due to 100000 nested stack frames
  4. D. It prints 0 because the recursion depth exceeds INT_MAX

Correct answer: C. Stack overflow / undefined behaviour / crash, due to 100000 nested stack frames

Each recursive call adds a new stack frame; with no tail-call optimisation guaranteed by the C standard (and this isn't in tail position anyway, since `n +` happens after the call returns), 100,000 nested frames will typically exhaust the call stack, causing a crash — this is undefined behaviour from stack exhaustion, not a computed answer.

More C Programming questions

Exams that ask this topic