How does comma operator work during assignment?

后端 未结 5 764
时光说笑
时光说笑 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条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 18:32

    Yes, that's exactly it: the compiler takes the last value. That's the comma operator, and it evaluates its operands left-to-right and returns the rightmost one. It also resolves left-to-right. Why anyone would write code like that, I have no idea :)

    So int b = (1, 2, 3) is equivalent to int b = 3. It's not a primitive list of any kind, and the comma operator , is mostly used to evaluate multiple commands in the context of one expression, like a += 5, b += 4, c += 3, d += 2, e += 1, f for example.

提交回复
热议问题