为什么用逗号双重初始化是非法的? [英] Why is this double initialization with a comma illegal?
问题描述
我有三个代码段.这个:
I have three code snippets. This one:
1,7; //yes, that's all the code
编译正常.这个:
double d = (1, 7);
也可以编译.然而这个:
also compiles okay. Yet this one:
double d = 1, 7;
无法编译.gcc-4.3.4说
fails to compile. gcc-4.3.4 says
错误:数字常量前应有预期的unqualified-id
error: expected unqualified-id before numeric constant
Visual C ++ 10说
and Visual C++ 10 says
错误C2059:语法错误:恒定"
error C2059: syntax error : 'constant'
为什么有这种区别?为什么这三个都不能用
进行编译,而在所有三个中都具有相同的效果?
Why such difference? Why don't all the three compile with ,
having the same effect in all three?
推荐答案
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.
最后一种情况类似于:
float x,y;
float a = 10, b = 20;
执行此操作时:
double d = 1, 7;
编译器期望变量标识符而不是数字常数.因此,这里7是非法的.
The compiler expects a variable identifier and not a numeric constant. Hence 7 is illegal here.
但是,当您这样做时:
double d = (1,7);
使用了普通的逗号运算符:1被求值并丢弃,而7存储在d中.
the normal comma operator is being used: 1 gets evaluated and discard while 7 is stored in d.
这篇关于为什么用逗号双重初始化是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!