简体   繁体   English

获得C语言的递归级别?

[英]obtain recursion level in C language?

I was writing a recursive function (in C language) and needed a way to know if the recursion had finished. 我正在用C语言编写一个递归函数,需要一种方法来知道递归是否完成。 I wonder if I can do it withought variables or flags. 我想知道我是否可以使用变量或标志来做到这一点。 With a function for example. 以功能为例。

For instance, if the recursion went 3 levels down and then came back up, is there a way to check if I am at level 1....withought using flags? 例如,如果递归递减了3级然后又重新升高,是否有办法检查我是否处于1级。

lev 1 -> lev 2 -> lev 3 -> lev 2 -> lev 1 (check here) lev 1-> lev 2-> lev 3-> lev 2-> lev 1(在这里检查)

You need to add an extra argument to your function, along the lines of int level . 您需要沿着int level的行向函数添加一个额外的参数。 Then pass level+1 when calling yourself recursively, and pass 0 (or 1 if you prefer) to the initial call. 然后在递归调用自己时传递level+1 ,并向初始调用传递0 (如果愿意,则传递1 )。

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. 但我怀疑的r解决方案极大地为你的问题更好。

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. 另一方面,这只是说要存储标志值的一种复杂方式。

也许您可以只检查调用堆栈,但这将取决于您要处理的实际级别或递归,否则,如果仅出于调试/理解的目的,请使用R ..解决方案。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM