3

I've the following two lines , and could not find a good explanation

I did read about the dual nature of comma as operator and separator , and priority precedence of parentheses , and comma as a sequence point .

int a =(3,4) // here a is 4 because comma here is an operator first a=3 , then a = 4 
int a={3,4} // here is the problem , should not a=3 and then a =4 too because comma is a sequence point or it's undefined behavior or what ?

I expected

a=4
a=4 , 
but the actual output is 
a=4 , a=3
dbc
  • 104,963
  • 20
  • 228
  • 340

1 Answers1

5

In the first case:

int a =(3,4);

The variable is initialized with an expression consisting of a comma operator and parenthesis. This expression evaluates to 4 as you correctly surmised which is what is assigned to a.

In the second case:

int a={3,4};

The variable is initialized with an initializer list which is what the curly braces denote, and the comma separates the initializers. If the variable in question was a struct or array, the values in the initializer list would be assigned to each member. If there are more initializers than members, the excess values are discarded.

So a is assigned the first value in the initializer list, namely 3, and the value 4 is discarded.

Had you done this:

int a[2] = {3, 4};

Then a[0] would be 3 and a[1] would be 4.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 4
    Nitpick: the standard says "The initializer for a scalar shall be **a single expression**, optionally enclosed in braces," where "expression" must be interpreted in light of the formal syntax as an `assignment-expression`, which cannot contain a comma operator at the outermost level. Thus the behavior of the OP's brace-enclosed initializer is *undefined*. It is not safe to assume that the extra initializer inside the braces will simply be discarded. It might, in fact, be used instead of the first by some implementations, and of course any manner of wilder behavior might also be observed. – John Bollinger Jul 09 '19 at 19:34