0

Why does this code compile ?

int X = (2,4);

I compiled this line with c++ replit

the second value (4) is assigned to X

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Chanoch
  • 45
  • 4
  • Read about [comma operator](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work). Also see [how `double d = (1, 7);` work](https://stackoverflow.com/questions/8519884/why-is-this-double-initialization-with-a-comma-illegal). – Jason Apr 04 '23 at 14:28
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to "search and then research" and you'll find plenty of related SO questions for this. – Jason Apr 04 '23 at 14:34

2 Answers2

2

The initializing expression is a praimary expression with the comma operator

int X = (2,4);

Its value is the value of the second operand of the comma operator.

In fact this declaration is equivalent to the declaration

int X = 4;

because the first operand has no side effect.

From the C++17 Standard (8.19 Comma operator)

1 The comma operator groups left-to-right.

expression: assignment-expression
expression , assignment-expression

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause 8). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a bit-field. If the right operand is a temporary expression (15.2), the result is a temporary expression.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

It will compile in c++. The only value that is applied is the last one when you use a parenthesis expression with multiple values inside, however all values will be evaluated which means you can do things like this in very specific cases:

int a, b;
a = (b = 3, 5);  // assigns 3 to b and 5 to a
Psonbre
  • 21
  • 1