++i?

I'm having trouble understanding why the output is 4... Can anyone explain? To my understanding,
this means i = i + i + 1, so i=3...

1
2
3
4
5
int i=1;

i+=++i;

cout<<i;
Last edited on
i += ++i
The increment comes first so:
First increment i by one i = 2
i = i + i = 2 + 2 = 4

This is an awful thing to do btw. Why are you doing this???
Last edited on
It's a sample exam to prepare for the final...Thanks for your answer!
Last edited on
1
2
int i=1;
i+=++i;

The behavior of this program is undefined (in other words, it's an error of the same kind as accessing an array out of bounds or dereferencing a null pointer). There is no explanation.

See http://en.cppreference.com/w/cpp/language/eval_order or any other material on expression evaluation rules in C++ (or C, same thing here)

PS: actually, I believe it is well-defined under C++11's slightly stricter rules.. but it's still a very bad idea.

I get the output of 3 on IBM xlC, and 4 from GNU g++
Last edited on
like mats said, it's the same as

i = (++i) + i;


and because it's prefix, it's done first, hence both terms on the right are 2.

If i saw anything like this in any of the code i'm working on i'd find the developer and set them on fire.
Last edited on
i = (++i) + i;

Does not look like

i+=++i;

I understand for this specific code... but do you have any tips if the code changes slightly? How to I go from the initial code to your simplified code?

Basically, if I see ++i in a compound statement, I place it before the other things?
Topic archived. No new replies allowed.