Recursive Fibonacci

Ian Burris picture Ian Burris · Oct 5, 2009 · Viewed 152.2k times · Source

I'm having a hard time understanding why

#include <iostream>

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
        return fib(x-1)+fib(x-2);
    }
}

int main() {
    cout << fib(5) << endl;
}

results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?

Answer

Georg Fritzsche picture Georg Fritzsche · Oct 5, 2009

When x==2 you call fib(1) and fib(0):

return fib(2-1)+fib(2-2);

Consider what will happen when fib(0) is evaluated...