The comma operator in the declaration

I am writing a C ++ parser (actually a small subset of it) and cannot find an explanation why the comma operator is not allowed when initializing variables.

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 ++ specification says that you can use an expression as an initializer in a variable declaration. Why is the binary comma expression not allowed, but all other expressions (with higher priority) 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 ++ specification states that an initializer can only contain an assignment expression. Is this the place that governs this assignment is the lowest priority allowed in initialization?

+4
source share
1 answer

The language grammar interprets commas in initializers as sentences of the declarator with comma-delimited ones, i.e. forms:

int i = 2, j = 3;

To avoid this ambiguity, you need to wrap the commas in parentheses.

From [dcl.decl] :

[...]
init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator
[...]
+4
source

Source: https://habr.com/ru/post/1690257/


All Articles