ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}
int main(void) {
    printf("%d", fibonacci(-5));
}
  1. A. It recurses forever (or until stack overflow), since n keeps decreasing without ever becoming positive
  2. B. Undefined behaviour: fibonacci is not designed for negative input
  3. C. It returns -5 immediately: -5 <= 1 is true, so the base case triggers right away with no further recursion at all
  4. D. Compile-time error: fibonacci cannot be called with a negative argument

Correct answer: C. It returns -5 immediately: -5 <= 1 is true, so the base case triggers right away with no further recursion at all

n <= 1 is checked FIRST, and -5 <= 1 is true, so the function returns n (-5) immediately without ever reaching the recursive case — there's no infinite recursion here, since the very first call already satisfies the base case. It just produces a nonsensical (but well-defined) negative Fibonacci value because the function was never designed to validate its input.

More C Programming questions

Exams that ask this topic