逗号运营商在声明中

The comma operator in a declaration

本文关键字:声明 运营商      更新时间:2023-10-16

我正在编写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

C 规格说您可以将表达式用作变量声明中的初始化器。为什么不允许逗号二进制表达,但是允许所有其他表达式(具有更高优先级)?cppreference.com(http://en.cppreference.com/w/cpp/language/initialization)说,任何表达式都可以用作初始化器。

C 规格的第8.5节说,初始化器只能包含分配表达。这是调节分配是初始化中允许的最低特定表达式的位置吗?

语言语法将初始化器中的逗号解释为逗号删除的宣言子句,即形式:

int i = 2, j = 3;

要避免这种歧义,您需要在括号中包裹逗号。

来自 [dcl.decl]

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