我很困惑,不知道这里发生了什么:
#include <iostream>
void recur();
int i = 1;
int main() {
recur();
}
void recur() {
std::cout << "\nvalue of i above while loop : " << i << std::endl;
while(i++ < 10) {
recur();
std::cout << "statement just after the recursive call to tester and here the value of i is :" << i << std::endl;
}
}
这是输出:
value of i above while loop : 1
value of i above while loop : 2
value of i above while loop : 3
value of i above while loop : 4
value of i above while loop : 5
value of i above while loop : 6
value of i above while loop : 7
value of i above while loop : 8
value of i above while loop : 9
value of i above while loop : 10
statement just after the recursive call to tester and here the value of i is :11
statement just after the recursive call to tester and here the value of i is :12
statement just after the recursive call to tester and here the value of i is :13
statement just after the recursive call to tester and here the value of i is :14
statement just after the recursive call to tester and here the value of i is :15
statement just after the recursive call to tester and here the value of i is :16
statement just after the recursive call to tester and here the value of i is :17
statement just after the recursive call to tester and here the value of i is :18
statement just after the recursive call to tester and here the value of i is :19
每次函数 recur
被调用时,它会打印它的第一行,当值等于 10 时,循环中断。现在当我们退出循环时,while 循环中的语句如何执行作品/版画?有人可以解释发生了什么吗?
让我验证一下
我的想法正确吗?在每次调用函数 recur
时,控制都会返回到函数定义的开头。例如:
while(i++<10) {
recur();
//...
}
|
|
\ /
void recur() { // here i is 2
while(i++ < 10) {
recur();
//....
}
}
|
|
\ /
void recur() { // here i is 3
while(i++ < 10) {
recur();
//....
}
}
这是通话的方式吗?
最佳答案
变量 i 继续递增,因为 while 条件必须再执行一次以确保它为假,导致 i 递增,即使它在每次调用 recur() 时都超过 10。
如果您将 i 的增量放在条件之外,结果会更符合您的预期。例如:
while (i < 10) {
i++;
// Do rest.
}
但是对于您当前的代码,每次测试条件时,即使条件为假,我也会继续递增。
关于c++ - 当初始条件为假时进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677855/