Recursive function with static variable

2019-03-29 08:23发布

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;
}

8条回答
Evening l夕情丶
2楼-- · 2019-03-29 09:13

Instead of using a static variable, simply pass count as an argument.

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

int main() {
    foo(0);
    foo(0);
}

Static variables and recursion do not generally go together.

查看更多
我命由我不由天
3楼-- · 2019-03-29 09:13
void foo() {
  ...
  if (count > 0) count--; // you can decrease it at then end of foo()
}
查看更多
登录 后发表回答