for 语句头的 init-statement 中不允许使用逗号运算符的表达式

Expression with comma operator is not allowed in the init-statment of for statement's header

...
for (int i = 1; i != 9; ++i)
 std::cout << i << std::endl;
...

for循环语句的头部由三部分组成:初始化语句、条件和表达式。在上面的例子中,初始化语句是 int i = 1;

似乎将带有逗号运算符的语句作为 init 语句包含在内是非法的。

...
for ( (int i , cin >> i) ; i != 9; ) // 2 Erros
 std::cout << i << std::endl;
...

对于上面的示例,我收到了 2 条错误警告

(int i , cin >> i) ; i != 9;) 错误:在 'int'

之前需要主表达式

(int i , cin >> i) ; i != 9;) 错误:i' 未在此范围内声明

谁能给我解释一下这个错误的原因是什么?

请记住,在声明符中您可以一次声明多个变量。 例如

int a,b,c,d;

在类型(token "int")之后你应该只使用标识符来声明变量。 在for的init-statement中可以使用多个逗号语句,但要分隔表达式,例如:

int a=2, b=3;
for (a=b+b, b=-a; a < b; a++){
    //....
}

逗号分隔符是非常允许的。试试这个

for (int i = 1,j=2; i != 9; ++i) std::cout << j << std::endl;

你做错的是在同一语句中声明了一个变量并为其获取了用户值。它通常也无效(不仅仅是在 init 中),因为它们是两个独立的语句,即声明语句和输入语句。因此应该用 semi-colon 分隔。所以试试

int i,cin>>i;

在外面,它也应该报错。 在问题逗号分隔符中发布的代码中 in play not comma operator.

简单:第一个语句必须是声明语句。

你同样不能写:

int main()
{
    (int i , cin >> i);
}

那里没有 "comma operator",只是一个语法错误,因为那不是 C++ 的工作方式。

我可能会找到错误的可能原因。

For operators that do not specify evaluation order, it is an error for an expression to refer to and change the same object

As a simple example, the << operator makes no guarantees about when or how its operands are evaluated. As a result, the following output expression is undefined:--138 pp C++ Primer 5th Ed.

 //Example from the book
 int i = 0;
 cout << i << " " << ++i << endl;

对于这种情况,如果逗号运算符左侧的 int i 指的是对象,则右侧的表达式会更改相同的对象 i

你的意思好像是

for ( int i = ( cin >> i, i ) ; i != 9; )

这是一个演示程序

#include <iostream>

int main() 
{
    for ( unsigned int i = ( std::cin >> i, i ); i != 0; --i )
    {
        std::cout << i << ' ';
    }

    std::cout << std::endl;

    return 0;
}

它的输出可能看起来像

10
10 9 8 7 6 5 4 3 2 1

正如您正确提到的,for 循环的第一部分是 init-satement,它可以是表达式或声明。您不能在 for 语句的这一部分使用逗号运算符组合声明和表达式。