Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function with static variable

I have a recursive function with a static variable "count". The function increments count recursively and since it has file scope, when I call foo() a second time, count is still equal to 5. Is there a technique to reset count to 0 before the second time foo() is called?

Basically, I don't want count to have file scope but I want it to retain its value through different iterations.

One way I can think of doing it is have an argument in foo() to initialize foo(). Such as foo(int count). But is there another way?

#include <iostream>

using namespace std;

void foo()
{
    static int count = 0;

    if(count<5)
    {
        count++;
        cout<<count<<endl;
        foo();
    }
    else
    {
        cout<<"count > 5"<<endl;
    }
}

int main()
{
    foo();  //increment count from 0 to 5
    foo();  //count is already at 5

    return 0;
}
like image 907
Steve Avatar asked Aug 22 '09 19:08

Steve


1 Answers

A more idiomatic way is to split it into two functions:

void foo() {
   foo_recursive(0);
}

void foo_recursive(int count) {
    if (count < 5) {
        count++;
        cout << count << endl;
        foo_recursive(count);
    } else {
        cout << "count > 5" << endl;
    }
}

Which has the benefit of not requiring the caller to supply an argument to foo() and also you don't need a static variable (which I always feel is a bad idea).

like image 74
waxwing Avatar answered Oct 04 '22 04:10

waxwing