Reputation: 21
I am supposed to count how many times the recursive function is called so I tried to make a global variable to make it count in the function then call it in main in function it works perfectly but when it's called in main somehow its value doesn't change dunno the reason
#include <iostream>
using namespace std;
int y;
long fib(int n){
static int x = -1;
x++;
y = x;
cout << y << endl;
if (n == 1){
return 1;
}
else if (n == 0){
return 0;
}
else
return fib(n - 1) + fib(n - 2);
}
int main(){
int N, X;
cin >> N;
while (N != 0){
cin >> X;
cout << "fib(" << X << ") = " <<fib(X) << " calls = "<< y << endl;
N--;
}
system("pause");
}
Upvotes: 2
Views: 203
Reputation: 141544
In the line:
cout << "fib(" << X << ") = " <<fib(X) << " calls = "<< y << endl;
there is no sequencing relation between fib(X)
and y
. Your compiler is allowed to read y
either before, or after, calling fib(X)
. (But not during!)
To fix this, change to:
cout << "fib(" << X << ") = " << fib(X);
cout << " calls = "<< y << endl;
This is a special case of the rule that there is no sequencing between arguments of a function call (remember that overloaded operators are actually calls to overloaded operator functions). For example, in func( a(), b() );
, a
and b
could be called in either order.
Upvotes: 3