How can I find the depth of a recursive function in C++

If you want it to be re-entrant and thread-safe, why not:

void rec(int &level)  // reference to your level var
{
   // do work

   rec(++level); // go down one level
}

main()
{
   //and you call it like
   int level=0;
   rec(level);

   cout<<level<<" levels."<<endl;
}

No static/global variables to mess up threading and you can use different variables for different recursive chains for re-entrancy issues.


You could use a static variable in the function...

void recursive()
{
 static int calls = 0;
 calls++;
 recursive();
}

Of course, this will keep counting when you start a new originating call....


Building on the answer already given by JoshD:

void recursive() 
{ 
    static int calls = 0;
    static int max_calls = 0;
    calls++;
    if (calls > max_calls)
        max_calls = calls;

    recursive();

    calls--;
}

This resets the counter after the recursive function is complete, but still tracks the maximum depth of the recursion.

I wouldn't use static variables like this for anything but a quick test, to be deleted soon after. If you really need to track this on an ongoing basis there are better methods.

Tags:

C++

Recursion