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
Alexey Frunze
source share