c++ - 当初始条件为假时进入循环

标签 c++ recursion

我很困惑,不知道这里发生了什么:

#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/

相关文章:

c++ - 另一个物体内部的复杂物体

scala - 我的 Scala 代码虽然通过了 @tailrec,但没有获得 TCO

c++ - 如何将向后打印数组的程序转换为打印第 N 个字符的递归程序?

java - 如何使用递归回溯 (Java) 找到特定迷宫的解决方案?

c++ - 复制到一个更大的变量

C++ 碰撞检测在最后一次检查时不起作用?

java - 如何修复此递归代码的执行?

c# - Pow(x,y) 函数的工作流程是什么?

c++ - 调用 Sendinput 后​​,在最小化/最大化/关闭窗口按钮上鼠标指针卡住

c++ - move 语义和临时隐式 this