递归函数中的全局变量如何保持为零?
因此,如果我有一个带有全局变量 var_: 的递归函数,
int var_;
void foo()
{
if(var_ == 3)
return;
else
var_++; foo();
}
然后我有一个调用 foo() 的函数,那么:
void bar()
{
foo();
return;
}
每次调用 foo 时设置 var_ =0 的最佳方法是什么?我知道我可以这样做:
void bar()
{
var_ =0;
foo();
return;
}
但我经常使用递归函数,我不想调用 foo 并忘记在以后设置 var_=0 。
有人对如何解决这个问题有什么建议吗?
谢谢,乔什
So if I have a recursive function with a global variable var_:
int var_;
void foo()
{
if(var_ == 3)
return;
else
var_++; foo();
}
and then I have a function that calls foo() so:
void bar()
{
foo();
return;
}
what is the best way to set var_ =0 everytime foo is called thats not from within itself. I know I could just do:
void bar()
{
var_ =0;
foo();
return;
}
but I'm using the recursive function a lot and I don't want to call foo and forget to set var_=0 at a later date.
Does anyone have any suggestions on how to solve this?
Thanks, Josh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将 foo() 转换为辅助函数。
您不必更改任何现有代码,仍然可以只调用
foo()
并让它完成工作。Turn
foo()
into a helper function.You won't have to change any existing code, and you can still just call
foo()
and let it do its work.我会将 foo() 拆分为初始化函数和真正的递归函数:
I would split
foo()
into an initializing function, and the true recursive function:要添加到您得到的前两个(惊人相似)答案中,请仅使 foo() 方法从类外部可见,并将 foo_helper() / foo_recur() 保持为私有(var_ 也应该是私有的)。如果这要在多线程环境中使用,您还应该使 foo() 同步。
另外,最好将“var_”称为实例变量或类变量(而不是“全局”)。
To add to the first two (amazingly similar) answers that you got, make only the foo() method visible from outside your class and keep the foo_helper() / foo_recur() as private (the var_ should also be private). If this is meant to be used in a multi-threaded environment, you should also make foo() synchronized.
Also, it's better to call "var_" an instance- or class- variable (instead of "global").
你真的需要这个全局变量吗?
如果它只是用来控制递归的深度,你可以用更优雅的方式重写它,如下:
Do you actually need this global variable?
If it's used only to control the depth of recursion, you can rewrite it in more elegant way, as follows:
为了让函数知道它是否是从自身内部调用的,您可以添加一个参数:
因此这种方法不需要添加辅助函数。
To let the function know whether it was called from within itself, you can add a parameter:
So this approach doesn't require adding a helper function.