“for"循环中的后增量和预增量产生相同的输出
以下 for 循环产生相同的结果,即使一个使用后增量,另一个使用预增量.
The following for loops produce identical results even though one uses post increment and the other pre-increment.
代码如下:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
我为两个for"循环得到相同的输出.我错过了什么吗?
I get the same output for both 'for' loops. Am I missing something?
推荐答案
i++
或 ++i
求值后,i
在这两种情况下都是一样的.前后自增的区别在于对表达式本身的求值结果.
After evaluating i++
or ++i
, the new value of i
will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i
递增 i
并计算为 i
的新值.
++i
increments i
and evaluates to the new value of i
.
i++
计算为 i
的旧值,并递增 i
.
i++
evaluates to the old value of i
, and increments i
.
这在 for 循环中无关紧要的原因是控制流的工作方式大致如下:
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
- 测试条件
- 如果为假,则终止
- 如果为真,则执行正文
- 执行增量步骤
因为(1)和(4)是解耦的,无论是前置还是后置都可以使用.
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
相关文章