c++ - 使用 ++ 运算符会导致意外结果
问题描述
我不明白为什么下面的两个代码会导致相同的结果。由于 n 首先递增,后者不应该从 6 打印到 10 吗?
编辑:我同时使用了 Visual Studio 2019 和 repl.it。
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; n++)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; ++n)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
解决方案
来自https://en.cppreference.com/w/cpp/language/for
attr(可选) for ( init-statement 条件(可选) ; 迭代表达式(可选) ) 语句
上面的语法产生的代码相当于:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
因此,您的两个 for 循环等效于
{
n;
while (n < 10) {
cout << n << endl;
n++;
}
}
和
{
n;
while (n < 10) {
cout << n << endl;
++n;
}
}
在 for 循环中:
- 第一条语句只执行一次
- 检查条件,如果为真
- 身体被执行
- 然后执行迭代表达式
- 转到 (2.)
如果您希望循环从 6 开始,则需要明确告诉它从 6 开始。
推荐阅读
- javascript - Ant Design 重置选择
- node.js - 如何在 Node.js 中更新 JSON 对象值
- r - 如何将第一级部分放在不同的 HTML 页面上?
- linux - Tortoise SVN 预提交脚本允许提交包含定义的字符串
- security - Firefox 无法建立连接 - websocket 和 heroku
- ruby - 如何使用 Gosu 库制作悬停效果
- ios - 如何在 iOS Swift4.2 中验证名称(John D'Largy)?
- extjs - 如何使用来自渲染器功能的记录作为编辑器 ExtJs Grid 内组合的存储
- c# - 重定向(url)不重定向
- ios - iOS - RxRealm - 即使数据集没有更改,是否可以获得更新的事件