int main() {
int x = 6;
x = x+2, ++x, x-4, ++x, x+5;
std::cout << x;
}
// Output: 10
int main() {
int x = 6;
x = (x+2, ++x, x-4, ++x, x+5);
std::cout << x;
}
// Output: 13
Please explain.
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.
Because
,has lower precedence than=. In fact,,has the lowest precedence of all operators.First case:
This is equivalent to
So,
xbecomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that isx-4value is calculated and discarded, then increment again, nowxis 10, and finally, another no-op. x is 10.Second case:
This is equivalent to
x+2is calculated, thenxis incremented and becomes 7, thenx - 4is calculated, thenxis incremented again and becomes 8, and finallyx+5is calculated which is 13. This operand, being the rightmost one, is the taken as the result of the whole comma expression. This value is assigned tox.x is 13.
Hope it’s clear.
And, as one of the comments suggests –
NEVER WRITE CODE LIKE THIS