Search code examples
c++comma-operator

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?


Solution

  • 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.