需要更好地了解循环-增量运算符 [英] Need to understand for loop better - post increment operator

查看:36
本文介绍了需要更好地了解循环-增量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太清楚我经常与for循环一起使用的后递增运算符.我对最新的帖子增量运算符的理解如下:

I was not really clear with the post increment operator that I always used with for loops. My latest and newly acquired understanding of post increment operator is the following:

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

有了这些新知识,我决定理解它/将其应用于我通常在 for 循环中使用后递增运算符的地方.现在好像我迷路了因为从理论上讲我最终输出的是错误的

Armed with this new knowledge i decided to understand/apply it to the places where i commonly used the post increment operator as in a for loop . Now it seems like I am lost since I am ending up with the wrong output theoretically

考虑以下代码

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,我哪里出错了?

Could anyone please clear my understanding and point me in the right direction. The output should be 0,1,2 where am i going wrong ?

推荐答案

您缺少的是何时 for 语句的每个部分都发生了:

What you're missing is when each of those sections of the for statement happen:

for (int i = 0 ; i < 3 ; i++)
//   111111111   22222   333

  • 第一位发生在任何迭代之前一次.
  • 第二个表达式在每次潜在迭代之前进行求值,如果为false,则不执行进一步的迭代.
  • 第三位在每次迭代的 end 处完成,然后返回以评估第二位.
    • The first bit happens once before any iterations are done.
    • The second expression is evaluated before each potential iteration and, if false, no further iterations are done.
    • The third bit is done at the end of each iteration, before returning to evaluate the second bit.
    • 现在,请仔细阅读最后一点. i ++ 在迭代的 end 中完成,在 cout<<之后的之后中完成.我.并且,在此之后,立即检查继续条件(第二部分).

      Now re-read that last bullet point carefully. The i++ is done at the end of an iteration, after the cout << i. And, immediately after that, the continuation condition is checked (the second part).

      因此循环实际上与以下内容相同:

      So the loop is effectively the same as:

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

      这就是为什么您获得 0 1 2 .

      这篇关于需要更好地了解循环-增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆