每次递归调用函数时,它都会有效地复制所需信息的新副本,然后继续。
你可以有一个“无限”重复的程序,即直到它耗尽资源,通常是堆栈空间——这些副本所在的空间。那看起来像
void recur(){
recur();
}
int main(){
recur();
exit(0); /* won't ever really get here.*/
}
显然,这不是很有用,因此您想编写一个对其重复频率有一定限制的程序。这是一个非常简单的程序来管理它:
#include <iostream>
using namespace std;
void recurSome(int count){
cout << "RecurSome called with " << count << endl;
if (count > 0){
recurSome(count-1);
cout << "Back at " << count << endl;
}else{
cout << "Bottom." << endl;
}
return;
}
int main(){
recurSome(10);
exit(0); /* now it will get here. */
}
如果您编译并运行它,请说:
bash $ g++ -Wall -o rc recursome.cpp
bash $ ./rc
你会得到结果:
RecurSome called with 10
RecurSome called with 9
RecurSome called with 8
RecurSome called with 7
RecurSome called with 6
RecurSome called with 5
RecurSome called with 4
RecurSome called with 3
RecurSome called with 2
RecurSome called with 1
RecurSome called with 0
Bottom.
Back at 1
Back at 2
Back at 3
Back at 4
Back at 5
Back at 6
Back at 7
Back at 8
Back at 9
Back at 10
bash $
看看它是如何被调用为 10,然后是 9,等等,然后在它到达底部后,它显示它返回 1,然后是 2,等等,直到 10?
基本规则是每个递归函数都应该有一些构成基本情况的东西,一个确实会再次调用自己的东西。在这个例子中,基本情况是count == 0
,事实上我们可以把它写成一个递归定义
recursome:
if c = 0 : print bottom
if c > 0 : print count, and recursome(c-1)
当您继续学习数学时,您会看到许多此类递归定义。
这是一个更漂亮的 C 版本,输出更好:
#include <stdio.h>
#include <stdlib.h>
int max = 10;
void recurSome(int count){
printf("RecurSome %*c Called with %d\n", max-count+1, ' ', count);
if (count > 0){
recurSome(count-1);
printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count);
}else{
printf("RecurSome %*c Bottom.\n", 2*max, ' ');
printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count);
}
return;
}
int main(){
recurSome(max);
exit(0); /* now it will get here. */
}
输出:
RecurSome Called with 10
RecurSome Called with 9
RecurSome Called with 8
RecurSome Called with 7
RecurSome Called with 6
RecurSome Called with 5
RecurSome Called with 4
RecurSome Called with 3
RecurSome Called with 2
RecurSome Called with 1
RecurSome Called with 0
RecurSome Bottom.
RecurSome Back at 0
RecurSome Back at 1
RecurSome Back at 2
RecurSome Back at 3
RecurSome Back at 4
RecurSome Back at 5
RecurSome Back at 6
RecurSome Back at 7
RecurSome Back at 8
RecurSome Back at 9
RecurSome Back at 10