在 C++ 中,在 For 循环中使用非递增变量是否可以接受?

Is it acceptable in C++ to have a non incremented variable in a For Loop?

所以我正在尝试学习 C++,并且遇到了这个循环:

if (userNumber >= 0) 
{
     for(double i = userNumber; i < userNumber + 10; i)
     {
         cout << ++i << endl;
     }
}

这与以下输出相同:

if (userNumber >= 0) 
{
     for(double i = userNumber; i < userNumber + 10; i++)
     {
         cout << i + 1 << endl;
     }
}

第一种形式可以接受,还是风格不好?

两者都有效,第二个更明确和可读。由于 ifor 循环块中未被修改,因此可以立即说出循环将迭代多少次。

C++标准中定义的for语句为:

for ( for-init-statement; optional condition; optional expression) statement

相当于

{
    for-init-statement
    while ( condition ) {
        statement
        expression ;
    }
}

except that names declared in the for-init-statement are in the same declarative-region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition.

所以两者都有效。但是第二个有更多的 C++ 风格,因为 expression 部分应该让你了解循环是如何控制的。

第一个片段的不良风格是有未使用的语句i。 在这种情况下更喜欢:

for(int i = userNumber; i < userNumber + 10; /*empty*/)
{
    cout << ++i << endl;
}

对于简单的情况,第二个片段越清晰越好。