Can someone explain to me why this code prints 14? I was just asked by another student and couldn’t figure it out.
int i = 5; i = ++i + ++i; cout<<i;
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.
The order of side effects is undefined in C++. Additionally, modifying a variable twice in a single expression has no defined behavior (See the C++ standard, §5.0.4, physical page 87 / logical page 73).
Solution: Don’t use side effects in complex expression, don’t use more than one in simple ones. And it does not hurt to enable all the warnings the compiler can give you: Adding
-Wall(gcc) or/Wall /W4(Visual C++) to the command line yields a fitting warning:Obviously, the code compiles to: