如何从递归函数调用另一个函数,只有一次,而无需使用静态变量? [英] how to call another function just once from recursive function without using the static variable?

查看:250
本文介绍了如何从递归函数调用另一个函数,只有一次,而无需使用静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例程序,我的问题,我使用的VisualStudio 2008

This is a sample program for my problem, I am using VisualStudio 2008

void abc()
{
    static int i = 0;
    if (i==0)
    {
        xyz();
        i++;
    }
    abc();
}

静态变量保留在明年调试会话值一还,因此不叫 XYZ(),我怎么能调用一个函数只有一次,而无需使用静态变量?

The static variable retain the value one in next debug session also, thus not calling xyz(), how can I call a function just once without using static variable??

推荐答案

这个怎么样:

void abc(int init)
{
    if(init == 1) xyz();
    abc(0);
}

int main(void) {
  abc(1);
}

它清楚地显示是怎么回事的优势。你甚至可以声明枚举:

It has the advantage of showing clearly what is going on. You could even declare an enum:

enum INIT {FIRST_TIME, RECURSING};

和做

void abc(enum INIT init) {
  if(init == FIRST_TIME) xyz();
  abc(RECURSING):
}

//$c$cpad.org/7euiC5LQ 您可以在 HTTP看到工作一个完整的例子一>

You can see a complete example at work at http://codepad.org/7euiC5LQ

#include <stdio.h>

enum INIT {FIRST, RECURSING};

void abc(enum INIT init) {
  if(init == FIRST) {
   printf("first time\n");
   abc(RECURSING);
  }
  else {
   printf("last time\n");
  }
}

int main(void) {
  abc(FIRST);
} 

在这个例子中,第二次是最后一次。很明显,你可以从那里美化;通常你会想一个参数传递到你的 ABC ,直到到达某一点,说可能与每个呼叫减少功能,这是递归的终结(想想阶乘,斐波那契等)。在这种情况下,通过无效参数(例如 1 )的初始调用将是一个很好的解决方案。你还是只有一个参数。

In this example, the second time is the last time. Obviously you can embellish from there; usually you will want to pass a parameter to your abc function that might decrease with each call until you reach some point that says "this is the end of the recursion" (think factorials, Fibonacci, etc). In that case, passing an "invalid" parameter (e.g. -1) for the initial call would be a good solution. You still have only one parameter.

最后 - 当您使用C ++,你可以考虑重载你的函数。带参数调用它,你包括 XYZ ;调用它没有,而你没有。有点像 abcStart 其他答案之一。但既然你标记你的问题C和C ++,并有在你的code,没有证据表明你真的打算C ++,我也不去那里...

Finally - when you are using C++, you could consider overloading your function. Call it with a parameter, and you include xyz; call it without, and you don't. A bit like the abcStart of one of the other answers. But since you tagged your question both C and C++, and there was no evidence in your code that you really intended C++, I am not even going there...

这篇关于如何从递归函数调用另一个函数,只有一次,而无需使用静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆