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

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

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.