[英]simple c++ loop prefix postfix operator
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int j = 5;
while ( ++j < 9)
cout << j++ << endl;
cin.get();
return 0;
}
So I am working on a book, and I understand how these things work, but I am seeking a more concrete explanation of why this prints 6 and 8. Please help me. 所以我正在写一本书,我理解这些东西是如何工作的,但我正在寻找一个更具体的解释,为什么这个打印6和8.请帮助我。
Thanks 谢谢
To understand what it outputs you need to step through the code: 要了解它的输出,您需要逐步完成代码:
j = 5
j = j + 1 // 6
j < 9 ? yes
output j // 6
j = j + 1 // 7
go to start of loop
j = j + 1 // 8
j < 9 ? yes
output j // 8
j = j + 1 // 9
go to start of loop
j = j + 1 // 10
j < 10 ? no
j
starts as 5. It then gets incremented to 6, then compared with 9 in in ++j < 9
. j
从5开始。然后增加到6,然后在++j < 9
与9进行比较。 This passes the condition, so we go to the next line, where it outputs 6 and then increments j
to 7. We go back to the conditional, j
is incremented to 8, which is still less than 9, then output, then j
is incremented to 9
, where the condition fails and the program ends. 这传递了条件,所以我们转到下一行,它输出6然后将
j
递增到7.我们回到条件, j
递增到8,仍然小于9,然后输出,然后j
是递增到9
,其中条件失败并且程序结束。
Given: 鉴于:
int j = 5;
while ( ++j < 9)
cout << j++ << endl;
Why are only 6
and 8
printed? 为什么只打印
6
和8
?
Upon entering the loop, j
is 5. Then the while (++j ...
increments that to 6. Then the cout
executes, printing out 6. Then the side effect of the j++
takes place, incrementing it to 7. 进入循环后,
j
为5.然后while (++j ...
其增加到6.然后cout
执行,打印出6.然后j++
的副作用发生,将其增加到7。
On the next iteration of the loop, the ++j
increments it again, giving 8
, which is then printed out. 在循环的下一次迭代中,
++j
再次递增它,给出8
,然后打印出来。 Then the side effect of the j++
takes place, incrementing j
to 9. 然后,产生的副作用
j++
发生,递增j
至9。
Then when while (++j < 9)
is executed again, j
has been incremented to 10, so the while
loop exits, and no more is printed. 然后,当再次执行
while (++j < 9)
时, j
已递增到10,因此while
循环退出,并且不再打印。
++j means the value of j is incremented by 1 and then used in the expression where it appears ++ j表示j的值加1 ,然后在出现的表达式中使用
j++ means the ( current ) value of j is used in the expression, after that j is incremented j ++表示j增加后,表达式中使用j的( 当前 )值
++j means increase j by one and then evaluate j. ++ j表示将j增加1,然后计算j。 j++ on the other hand means evaluate j first and then increase it by 1.
另一方面,j ++意味着首先评估j,然后将其增加1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.