Why is this double initialization with a comma illegal?

戏子无情 提交于 2019-12-01 04:13:08

问题


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?


回答1:


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:

float x,y;
float a = 10, b = 20;

When you do this:

double d = 1, 7;

The compiler expects a variable identifier and not a numeric constant. Hence 7 is illegal here.

However when you do this:

double d = (1,7);

the normal comma operator is being used: 1 gets evaluated and discard while 7 is stored in d.




回答2:


The difference is that in 1, 7; and (1, 7) you have expressions where a comma operator is allowed.

Your last example

double d = 1, 7; 

is a declaration, where the comma isn't an operator but a separator. The compiler exepcts something like

double d = 1, e = 7; 

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.




回答3:


  1. double d = (1, 7); Here the (1, 7) will be evaluated first; the comma works as sequential-evaluation operator, and 7 will be assigned to d.

  2. double d = 1, 7; In this case there is a problem: the part before 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.




回答4:


I believe it is because the last one is treated as (incorrect) declaration line: (double d = 1), (7)



来源:https://stackoverflow.com/questions/8519884/why-is-this-double-initialization-with-a-comma-illegal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!