Global variable in a recursive function how to keep it at zero?

Posted by Grammin on Stack Overflow See other posts from Stack Overflow or by Grammin
Published on 2011-01-12T17:43:24Z Indexed on 2011/01/12 17:53 UTC
Read the original article Hit count: 164

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about design