0

I have a function that I call recursively, but I want to keep track of a maximum through the entire process.

This is what I am doing:

void Intersect(double &MaxDistance)
{
  if(something)
    MaxDistance = something;
Intersect(MaxDistance);
}

Is that correct/reasonable? Something doesn't seem to be working and I'm having a hard time debugging because it's recursive (and I've rarely dealt with recursive functions).

Any suggestions?

Thanks,

Dave

4
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by vmanes
0

Print MaxDistance to the console so that you can keep track of the stack. Then analyze the output.
Or, better, Debug it. I mean, run the program step by step and see how the variable MaxDistance changes and how the condition "something" and the assignment "something" works

0

A recursive function needs a base case - something that will cause it to stop recursing.

That said, your general idea of storing the MaxDistance in the reference parameter will work - all attempts to compare to/store to the variable will be access the same memory object, no mater the level of recursion.

As a small demonstration, consider this:

void Intersect(double &MaxDistance, int counter)
{
   int n;

   if( counter == 20 )
      return;
   else
   {
      n = rand( ) % 1000;
      if( n > MaxDistance )
         MaxDistance = n;
      cout << MaxDistance << endl;
      Intersect(MaxDistance, ++counter);
   }
}

where the counter argument passed in can be initially 0. That's just an artificial way to make this stop - in your application you probably will have some value of MaxDistance that is a limit?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.