这个程序递归地调用函数tester。
#include <iostream>
void tester();
int i = 1;
int k = 1;
int main() {
tester();
}
void tester() {
while(i++ < 10)
tester();
std::cout << "called " << k++ << " times" << std::endl;
}我对这一产出感到惊讶:
called 1 times
called 2 times
called 3 times
called 4 times
called 5 times
called 6 times
called 7 times
called 8 times
called 9 times
called 10 times因为这就是我理解这个程序的方式
从main第一次调用测试器之后,它进入一个循环。循环的第一条语句再次调用函数tester,这将携带on.After循环10次,而while循环后面的语句应该只工作一次,即只工作一次。所以输出应该是:called 1 times。但这不是真的发生!为什么?这个程序是如何工作的?
发布于 2011-10-06 11:44:42
测试器被执行了十次,所以过程std::cout也被使用了十次。
由于递归,测试器的最后一次调用首先返回,因此打印顺序实际上被反转为调用顺序。
编辑:试试这段代码,也许它能帮你理解(对不起,它不是很漂亮,只是快速攻击):
#include <iostream>
void tester();
void print_indent(int cnt);
int i = 1;
int k = 1;
int recursion_level = 0;
int call_num = 0;
int main() {
tester();
}
void tester() {
int my_call = call_num++;
print_indent(recursion_level);
std::cout << "start of tester " << my_call << std::endl;
recursion_level++;
while(i++ < 10)
tester();
print_indent(recursion_level);
std::cout << "called " << k++ << " times" << std::endl;
recursion_level--;
print_indent(recursion_level);
std::cout << "end of tester " << my_call << std::endl;
}
void print_indent(int cnt) {
for (int i = 0; i < cnt; i++)
std::cout << " ";
}发布于 2011-10-06 11:45:59
一旦递归调用启动,当前函数就会冻结,直到该调用返回为止。因此,您的函数首先执行递归调用,然后打印。
因此,第一次打印将出现在称为最新的函数中。一旦最新调用的函数打印并返回,所有以前的调用都将开始打印和返回,直到最早的被调用函数退出为止。
发布于 2011-10-06 12:03:36
这就是递归的本质。当tester()自身调用时,它构建一个调用堆栈,然后在每个函数返回时打印消息。每次测试器返回时,它都会打印消息,这将因为while循环而发生10次。我把它想象成这样:
i k
--- --- ---
1 1 + tester()
2 1 | + tester()
3 1 | | + tester()
4 1 | | | + tester()
5 1 | | | | + tester()
6 1 | | | | | + tester()
7 1 | | | | | | + tester()
8 1 | | | | | | | + tester()
9 1 | | | | | | | | + tester()
10 1 | | | | | | | | | + tester()
11 1 | | | | | | | | | + "called 1 times"
12 2 | | | | | | | | + "called "2" times"
13 3 | | | | | | | + "called 3 times"
14 4 | | | | | | + "called 4 times"
15 5 | | | | | + "called 5 times"
16 6 | | | | + "called 6 times"
17 7 | | | + "called 7 times"
18 8 | | + "called 8 times"
19 9 | + "called 9 times"
20 10 + "called 10 times"https://stackoverflow.com/questions/7673709
复制相似问题