Post-increment and pre-increment within a #39;for#39; loop produce same output(“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.
这篇关于“for"循环中的后增量和预增量产生相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“for"循环中的后增量和预增量产生相同的输
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
