# Thread: Two pre increment in one expression

1. ## Two pre increment in one expression

Dear all
Please see this part of code:
int p=0,q=0;
q= ++p + ++p;

It is expected for q to be 3 after the expression, 1+2..
But it becomes 4,2+2..
Could not understand the background logic of the compiler
If you say :
q= ++p + 0 + ++p;
Or:
q= ++p + 1 + ++p;
In both forms q becomes 4..
Any one has any idea about the logic of this calculation?
Thank you all

2. It's not expected. That is undefined behaviour so it can give any answer it wants to

3. This is an example of how UB can mess with your mind / code / life.

Same code, different compilers, different answers.
It's undefined

4. Why are you doing this anyway? I'm guessing it came in a school test that wants to check if one has understood pre-increment and post-increment.
I've learnt by being on this forum that this results in Undefined Behaviour and there's a Wiki doc you can refer to about it.

My teacher at school says "For such kind of questions, perform all evaluations first and then add up the results." She means to say:
For q = ++p + ++p, do the ++p's first. That makes p=2. Now, you're adding the value of p which gives you 4. But this obviously doesn't make sense. Have a look at Salem's reply on the link he shared. With different compiler settings, you can yield different results. I've got both answers 3 and 4 after changing my compiler settings on C::B but neither of them can actually be considered the correct answer as the behaviour itself is "undefined".

If you do something like P = ++P, then too the result is undefined even though the compiler happily compiles it without any error as you are basically doing a double assignment of the same variable (P = P = P+1).

For expressions like "cout << ++p << p << p++" (p is initially 0), you'd expect a result "111" but I've learnt that such expressions are evaluated right to left yielding a theoretical result "012". I've gotten different results on Borland and GCC which makes this undefined behaviour too I guess (I'm not sure, but is this too undefined behaviour @Salem @Hodor?)

5. Well you need to know what a sequence point is, and the "object modified at most once" rule.
Question 3.8