简体   繁体   English

声明中的逗号运算符

[英]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. 我正在编写一个C ++解析器(实际上是它的一小部分),并且找不到为什么在变量初始化中不允许使用逗号运算符的解释。

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. C ++规范说你可以在变量声明中使用表达式作为初始化器。 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. cppreference.com( http://en.cppreference.com/w/cpp/language/initialization )表示任何表达式都可以用作初始化程序。

Section 8.5 of the C++ spec says that initializer can contain assignment-expression only. C ++规范的第8.5节说初始化程序只能包含赋值表达式。 Is this the place that regulates that assignment is the lowest-precedence expression allowed in the initialization? 这是调节该赋值是初始化中允许的最低优先级表达式的地方吗?

The language grammar interprets commas in initializers as comma-delimited declarator clauses, ie of the form: 语法语法将初始化器中的逗号解释为逗号分隔的声明符子句,即形式:

int i = 2, j = 3;

To avoid that ambiguity, you need to wrap comma-expressions in parentheses. 为避免这种歧义,您需要在括号中包含逗号表达式。

From [dcl.decl] : 来自[dcl.decl]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM