首页 > 解决方案 > 使用 ++ 运算符会导致意外结果

问题描述

我不明白为什么下面的两个代码会导致相同的结果。由于 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

标签: c++

解决方案


来自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 循环中:

  1. 第一条语句只执行一次
  2. 检查条件,如果为真
  3. 身体被执行
  4. 然后执行迭代表达式
  5. 转到 (2.)

如果您希望循环从 6 开始,则需要明确告诉它从 6 开始。


推荐阅读