How to track recursion depth?

I have a recursive function that I was looking for. I want to infer the recursion depth ... i.e. how many times the function calls itself.

If I use a static variable that increases at the top of the function and decreases at the bottom.

Will it definitely give me a depth level?

recurse() { static int depth = 0; depth++; /* do stuff recurse() */ depth--; return return_value; } 
+7
source share
7 answers
 recurse(int depth = 0){ .... recurse(depth+1); } 
+8
source

Make it easier and

<sub> If you really stretch your imagination, this may make it easier for the compiler to embed some recursive calls and / or perform tail call optimization in the case of tail recursion. I have no evidence that this plays a role, but I can provide a link to external characters from within the body of the function that affects compiler optimization. Sub>

I suggest:

 stuff recurse(int level=0) { //... recurse(level+1); //... (return stuff?) //... (throw exceptions?) //... recurse(level+1); //... (return stuff?) } 
+7
source

No, this may not be the case if an exception is thrown. Better (and more common) option:

 int recurse(int depth=0) { recurse(depth+1) return return_value; } 
+5
source

If you want to do this non-intrusively, you can ask your compiler to make all your calls, for example. with gcc:

 #include <iostream> static __thread int depth=-1; extern "C" { void __cyg_profile_func_enter (void *, void *) __attribute__((no_instrument_function)); void __cyg_profile_func_exit (void *, void *) __attribute__((no_instrument_function)); void __cyg_profile_func_enter (void *func, void *caller) { depth++; } void __cyg_profile_func_exit (void *func, void *caller) { depth--; } } class Foo { public: void bar() { std::cout << "bar: " << depth << std::endl; } }; int main() { Foo f; f.bar(); return 0; } 

To do this, you need to compile with -finstrument-functions .

+2
source

In one stream context, it will work.

0
source

Usually you want to increase the value of a variable depth, which is defined outside the recursive function for thread safety purposes and print it from outside the function.

A simple factorial example is shown here:

 #include <stdio.h> unsigned factorial(unsigned x, unsigned* depth) { if (x <= 1) return 1; ++*depth; return x * factorial(x - 1, depth); } int main(void) { unsigned depth, f; depth = 0; f = factorial(1, &depth); printf("factorial=%u, depth=%u\n", f, depth); depth = 0; f = factorial(2, &depth); printf("factorial=%u, depth=%u\n", f, depth); depth = 0; f = factorial(6, &depth); printf("factorial=%u, depth=%u\n", f, depth); return 0; } 

Output:

 C:\>recdep.exe factorial=1, depth=0 factorial=2, depth=1 factorial=720, depth=5 
0
source

Yes, it should work. I do not see any problems with this.

-one
source

All Articles