Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this double initialization with a comma illegal?

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?

like image 511
sharptooth Avatar asked Dec 15 '11 12:12

sharptooth


3 Answers

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.

like image 103
sharjeel Avatar answered Nov 15 '22 06:11

sharjeel


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.

like image 44
Bo Persson Avatar answered Nov 15 '22 05:11

Bo Persson


  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.

like image 29
kol Avatar answered Nov 15 '22 06:11

kol