【发布时间】:2017-12-05 10:12:45
【问题描述】:
我正在编写一个 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 = 1, 2, j = 3;时,它们会将它们留在哪里? -
"这是规定赋值是初始化中允许的最低优先级表达式的地方吗?"是的。
-
@n.m.但是有什么理由不允许逗号表达吗?
-
是的:为了消除与
int i = 2, j = 3的歧义。 -
@n.m.哦,现在我明白了。谢谢!
标签: c++