为什么用逗号进行双重初始化是非法的?
我有三个代码片段。这个:
1,7; //yes, that's all the code
编译没问题。这个:
double d = (1, 7);
也可以编译。然而这个:
double d = 1, 7;
无法编译。 gcc-4.3.4 说
错误:数字常量之前应有非限定 ID
,Visual C++ 10 表示
错误 C2059:语法错误:“常量”
为什么会有这样的差异?为什么这三个都不用 编译,
在这三个中具有相同的效果?
I have three code snippets. This one:
1,7; //yes, that's all the code
compiles okay. This one:
double d = (1, 7);
also compiles okay. Yet this one:
double d = 1, 7;
fails to compile. gcc-4.3.4 says
error: expected unqualified-id before numeric constant
and Visual C++ 10 says
error C2059: syntax error : 'constant'
Why such difference? Why don't all the three compile with ,
having the same effect in all three?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在前两种情况下,语句使用 C++ 的 逗号运算符
在后一种情况下,逗号被用作单独的变量,编译器希望您声明多个标识符;此处不使用逗号作为运算符。
最后一种情况类似于:
当您执行此操作时:
编译器需要变量标识符而不是数字常量。因此 7 在这里是非法的。
然而,当你这样做时:
正在使用普通的逗号运算符:1 被评估并丢弃,而 7 存储在 d 中。
In the first two cases, the statements are using C++'s comma operator
In the latter case, comma is being used as variable separate and the compiler is expecting you to declare multiple identifiers; the comma is not being used as the operator here.
The last case is similar to something like:
When you do this:
The compiler expects a variable identifier and not a numeric constant. Hence 7 is illegal here.
However when you do this:
the normal comma operator is being used: 1 gets evaluated and discard while 7 is stored in d.
区别在于,在
1, 7;
和(1, 7)
中,表达式中允许使用逗号运算符。最后一个示例
是一个声明,其中逗号不是运算符而是分隔符。编译器期望类似这样的内容
,这将是正确的变量声明。
请注意,逗号有时是一个运算符(在表达式中),但也可以在其他地方用作分隔符,例如函数声明中的参数列表。
The difference is that in
1, 7;
and(1, 7)
you have expressions where a comma operator is allowed.Your last example
is a declaration, where the comma isn't an operator but a separator. The compiler exepcts something like
which would be a correct variable declaration.
Note that the comma is sometimes an operator (in expressions), but is also used as a separator in other places like parameter lists in function declarations.
double d = (1, 7);
这里将评估(1, 7)
第一的;逗号用作顺序求值运算符,并且
7
将被分配给d
。double d = 1, 7;
在这种情况下有一个问题:该部分逗号之前意味着您声明一个 double 并设置其值,但是
逗号后面的部分是无意义,因为它只是一个
整数常量。
double d = (1, 7);
Here the(1, 7)
will be evaluatedfirst; the comma works as sequential-evaluation operator, and
7
will be assigned tod
.double d = 1, 7;
In this case there is a problem: the partbefore the comma means you declare a double and set its value, but
the part after the comma is meaningless, because it's just a single
integer constant.
我相信这是因为最后一个被视为(不正确的)声明行:
(double d = 1), (7)
I believe it is because the last one is treated as (incorrect) declaration line:
(double d = 1), (7)