Please help me with this.
I tried to run this code:
#include<iostream>
using namespace std;
int numcalls=0;
int fibonacci(int n)
{
numcalls++;
if(n == 0 || n == 1)
{
return 1;
} else{
return fibonacci(n-2) + fibonacci(n-1);
}
}
int main()
{
cout<<fibonacci(2)<<endl<<numcalls;
return 0;
}
In output its showing value of numcalls as 0
but when i try counting how many times a function is called with the code given below, it works fine :
#include<iostream>
using namespace std;
intnumCalls = 0;
voidfoo() {
++numCalls;
}
intmain() {
foo(); foo(); foo();
cout << numCalls << endl;
}
The problem is that you on this line cout<<fibonacci(2)<<endl<<numcalls; have both fibonacci(2) and numcalls in the same statement. The compiler is allowed to evaluate numcalls before it evaluates fibonacci(2).
To make sure fibonacci(2) is evaluated before numcalls you should split the statement in two.
1 2
cout << fibonacci(2) << endl;
cout << numcalls;
You can still put it on the same line if you prefer.