Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

recursion

How can I find the current depth inside a recursive function in C++ without passing in the previous level? i.e. is it possible to know how many times the function was called without using a parameter to keep track of the level and passing that number in as a parameter each time the function is called?

For example my recursive function looks like this:

DoSomething(int level)
{
  print level;
  if (level > 10)
    return;
  DoSomething(++level);
}

main
{
  DoSomething(0);
}
like image 745
Arizona1911 Avatar asked Oct 29 '10 22:10

Arizona1911


1 Answers

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.

like image 162
Mark Ransom Avatar answered Nov 15 '22 16:11

Mark Ransom