gpt4 book ai didi

c++ - 需要更好地理解 for 循环 - 后增量运算符

转载 作者:IT老高 更新时间:2023-10-28 22:32:09 25 4
gpt4 key购买 nike

我不太清楚我一直用于 for 循环的后增量运算符。我对后增量运算符的最新和新获得的理解如下:

int a = 5
int b = a++ //a will increment and return back its old value 5
so b = 5

有了这些新知识,我决定将其理解/应用到我经常使用后递增运算符的地方,例如 for 循环。现在好像我迷路了因为理论上我最终得到了错误的输出

考虑下面的代码

for(int i=0 ; i< 3 ; i++)
{
std::cout << i;
}

第一个循环

i starts with 0 which is less than 3 so ( increment by 1 however since its i++ it returns old value 0) 
so cout should display 1 // But it displays 0

第二次循环

 i is now 1 which is less than 3 so i++ is applied - Now i is 2 and returns back 1
so cout should display 2 //But it display 1

第三次循环

 i is now 2 which is less than 3 so i++ is applied - Now i is 3 and returns back 2
so cout should display 3 //But it display 2

第四循环

 i is now 3 which is not less than 3 so loop exits

谁能澄清我的理解并指出正确的方向。输出应该是 0,1,2 我哪里出错了?

最佳答案

您缺少的是何时 for 的每个部分声明发生:

for (int i = 0 ; i < 3 ; i++)
// 111111111 22222 333
  • 任何次迭代完成之前发生一次
  • 在每次潜在迭代之前计算第二个表达式,如果为假,则不再进行迭代。
  • 第三位在每次迭代的结束完成,然后返回计算第二位。

现在仔细阅读最后一个要点。 i++在迭代的结束 cout << i 之后完成.并且,紧接着,继续条件被检查(第二部分)。

所以循环实际上是一样的:

{   // Outer braces just to limit scope of i, same as for loop.
int i = 0;
while (i < 3) {
cout << i;
i++;
}
}

这就是为什么你会得到 0 1 2 .

关于c++ - 需要更好地理解 for 循环 - 后增量运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26034374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com