How does comma operator work during assignment?

后端 未结 5 757
时光说笑
时光说笑 2020-12-06 17:46
int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
  1. Is (1,2,3) some sort of structure in c++ (some pri
5条回答
  •  萌比男神i
    2020-12-06 18:22

    (1,2,3) is an expression using two instances of the comma operator. The comma operator evaluates its left operand, then there's a sequence point and then it evaluates its right operand. The value of the comma operator is the result of the evaluation of the right hand operand, the result of evaluating the left operand is discarded.

    int b = (1,2,3);
    

    is, therefore, equivalent to:

    int b = 3;
    

    Most compilers will warn about such a use of the comma operand as there is only ever a point to using a comma operator if the left hand expression has some side effect.

提交回复
热议问题