开发者

obtain recursion level in C language?

开发者 https://www.devze.com 2023-03-05 07:45 出处:网络
I was writing a recursive function (in C language) and needed a way to know if the recursion had finished. I wonder if I can do it withought variables or flags. With a function for example.

I was writing a recursive function (in C language) and needed a way to know if the recursion had finished. I wonder if I can do it withought variables or flags. With a function for example.

For instance, if the recursion went 3 levels do开发者_运维百科wn and then came back up, is there a way to check if I am at level 1....withought using flags?

lev 1 -> lev 2 -> lev 3 -> lev 2 -> lev 1 (check here)


You need to add an extra argument to your function, along the lines of int level. Then pass level+1 when calling yourself recursively, and pass 0 (or 1 if you prefer) to the initial call.


if you want to play with stack ...

int  func(void *p,int n, int stacksize)
{
 char marker;
 int depth =  (int)p -(int)&marker ;
 printf("%d --- %d --- %d\r\n", n,depth, stacksize?depth/stacksize:0);
 if (n>10)
    return depth ;

 return func(p,n+1,stacksize);
}


int main()
{
  char marker;
  int onepass = func(&marker,11,0);

  func(&marker,0,onepass );
  return 0;
}


If you don't care about portability, you can unwind the call-stack manually. But I suspect R's solution is vastly better for your problem.


The answer depends on the actual problem. Without storing some sort of flag, you can't tell (in a portable way, that is).

However, it's possible that your recursive function happens to alter some data in such a way that it can tell whether it has previously already entered into a certain recursion depth. On the other hand, this is just a complicated way of saying that you're storing a flag value.


Maybe you can just check the call stack, but it will depend on the real level or recursion you are dealing with, else if it's for debug/understanding purpose only, go with R.. solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消