Global variable in a recursive function how to keep it at zero?
So if I have a recursive function with a global variable var_:
开发者_JS百科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
Turn foo()
into a helper function.
void foo() {
var_ = 0;
foo_helper();
}
void foo_helper() {
if(var_ == 3)
return;
else
var_++; foo_helper();
}
You won't have to change any existing code, and you can still just call foo()
and let it do its work.
I would split foo()
into an initializing function, and the true recursive function:
void foo()
{
var_ = 0;
foo_recur();
}
void foo_recur()
{
if(var_ == 3)
return;
else
var_++; foo_recur();
}
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:
void foo() {
fooHelper(0);
}
void fooHelper(int var) {
if (var == 3) return;
else fooHelper(var + 1);
}
To let the function know whether it was called from within itself, you can add a parameter:
int var_;
void foo(boolean from_itself)
{
if(!from_itself)
var_ = 0;
if(var_ == 3)
return;
else
var_++; foo(true); // from within itself
}
void bar()
{
foo(false); // not from within itself
return;
}
So this approach doesn't require adding a helper function.
精彩评论