関数を再帰的に呼び出すたびに、必要な情報の新しいコピーが効果的に作成され、続行されます。
「無限に」繰り返されるプログラム、つまり、リソース、通常はスタックスペース、つまりそれらのコピーが送信されるスペースがなくなるまで、プログラムを作成できます。それは次のようになります
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:
c = 0の場合:
c> 0の場合に下部を印刷:カウントを印刷し、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