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?
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...