Search code examples
c++recursionglobal-variablesfibonacci

Eclipse c++ not letting me use global variable?


I'm trying to make this recursive program count how many times it calls itself, and I was going to use a global variable to keep count but eclipse isn't recognizing it for some reason. Here's my code:

#include <iostream>
#include <cstdlib>
using namespace std;

int count = 0;

int fib(long int);


int main()
{
    long int number;
    cout << "Enter a number => ";
    cin >> number;
    cout << "\nAnswer is: " << fib(number) << endl;
    return 0;
}

int fib (long int n)
{
    //cout << "Fibonacci called with: " << num << endl;
    if ( n <0 )
    {
        cout <<" error Invalid number\n";
        exit(1);
    }
    else if (n == 0 || n == 1)
        return 1;
    else{
        count++;
        return fib(n-1) + fib(n-2);}
    cout << count;

}

Whenever I initially declare count, it doesn't even recognize it as a variable, does anybody know the reason for this?


Solution

  • Your problem is here:

    using namespace std;
    

    It brings in std::count from the algorithm header, so now count is ambiguous. This is why people are told not to do using namespace std;. Instead, remove that line and put std::cout instead of cout (and the same for cin and endl).