blcArmadillo blcArmadillo - 1 year ago 90
C++ Question

Recursive Fibonacci

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download