我正在编写一个 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
[...]
关于c++ - 声明中的逗号运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47651014/