Elviss Strazdins
Elviss Strazdins

Reputation: 1474

The comma operator in a declaration

I am writing a C++ parser (actually a small subset of it) and can't find an explanation to why comma operator is not allowed in a variable initialization.

int a = 1, 2; // throws a "Expected ';' at the end of declaration" compiler error
a = 1, 2; // assigns the result of the comma binary operator to the a (2)
int a = (1, 2); // does the same as above, because paren expression is allowed as an initializer

The C++ spec says that you can use an expression as an initializer in a variable declaration. Why is comma binary expression not allowed but all the other expressions (with higher precedence) are allowed? cppreference.com (http://en.cppreference.com/w/cpp/language/initialization) says that any expression can be used as an initializer.

Section 8.5 of the C++ spec says that initializer can contain assignment-expression only. Is this the place that regulates that assignment is the lowest-precedence expression allowed in the initialization?

Upvotes: 5

Views: 1799

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

The language grammar interprets commas in initializers as comma-delimited declarator clauses, i.e. of the form:

int i = 2, j = 3;

To avoid that ambiguity, you need to wrap comma-expressions in parentheses.

From [dcl.decl]:

[...]
init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator
[...]

Upvotes: 4

Related Questions