int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
- Is
(1,2,3)some sort of structure in c++ (some primitive type of list, maybe?) - Why is
bassigned the value3? Does the compiler simply take the last value from the list?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 toint 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, likea += 5, b += 4, c += 3, d += 2, e += 1, ffor example.