Search code examples
c++for-loopcomma-operator

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;
...

The header of a for loop statement consists of three parts: an init-satement, a condition and an expression. In the case above, the init-statement is int i = 1;

Seems it is illegal to include a statement with a comma operator as the init-statement.

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

For the example above, I've received 2 error warnings

(int i , cin >> i) ; i != 9;) Error: Expected primary-expression before 'int'

(int i , cin >> i) ; i != 9;) Error: i' was not declared in this scope

Can someone please explain to me what's the reason for the bug?


Solution

  • Simple: that first statement must be a declaration statement.

    You likewise cannot write:

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

    There is no "comma operator" there, just a syntax error, because that is not how C++ works.