带有静态变量的递归函数 [英] Recursive function with static variable
问题描述
我有一个带有静态变量count"的递归函数.该函数递归地递增计数,并且由于它具有文件作用域,当我第二次调用 foo() 时,计数仍然等于 5.是否有一种技术可以在第二次调用 foo() 之前将计数重置为 0?>
基本上,我不希望 count 具有文件范围,但我希望它通过不同的迭代保留其值.
我能想到的一种方法是在 foo() 中有一个参数来初始化 foo().如 foo(int count).但是还有别的方法吗?
#include 使用命名空间标准;空 foo(){静态整数计数 = 0;如果(计数<5){计数++;cout<<计数<5"<
更惯用的方式是将其拆分为两个功能:
void foo() {foo_recursive(0);}void foo_recursive(int count) {如果(计数<5){计数++;cout<<计数<<结束;foo_recursive(计数);} 别的 {cout<<计数>5"<<结束;}}
这样做的好处是不需要调用者为 foo()
提供参数,而且你也不需要静态变量(我一直觉得这是个坏主意).>
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;
}
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).
这篇关于带有静态变量的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!