++ Prefix Operator

I do not understand why the below program is displaying 22. As I understand it should be 21 as 6 + 7 + 8 = 21. But It is giving output as 22.

Can anyone please help me to understand it?

1
2
3
4
5
6
7
8
9
  int main()
{
    int i = 5;
    i = ++i + ++i + ++i;
    printf("%d", i);

    getchar();
    return 0;
}
++i and i++ are different because you increment it before the number is changed right?
So here it would make sense that:
++i(5+1) + ++i((5+1)+1) + ++i((5+1)+1)+1) and another +1 because you add another one to the value of i itself(the new value)
so instead of 21, there is another increment of 1, so 22.
see http://www.cplusplus.com/doc/tutorial/operators/ for more info.
@ rjvc Thank you very much for the reply.
That is undefined behaviour.

You have A + B + C.
We know that the code has to evaluate A and B before A + B
and that C and A + B have to be evaluated before X + C.
Other than those restrains, the order of evaluations is up to implementation; it could return 24 too.

In other words, do not attempt multiple ++ or -- for same variable in one expression.
That's what I thought as well. On my compiler it returns 21 and a "stern" warning :)
@ keskiverto Thanks for the advise.
Topic archived. No new replies allowed.