“for"循环中的后增量和预增量产生相同的输出 [英] Post-increment and pre-increment within a 'for' loop produce same output

查看:26
本文介绍了“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. 测试条件
  2. 如果为假,则终止
  3. 如果为真,则执行正文
  4. 执行增量步骤

因为(1)和(4)是解耦的,无论是前置还是后置都可以使用.

Because (1) and (4) are decoupled, either pre- or post-increment can be used.

这篇关于“for"循环中的后增量和预增量产生相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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