Error

Hi. I was wondering why this piece of code:

1
2
3
  int a=1, b;
  b= ++a + ++a + ++a;
  cout << b;

outputs 10 instead of 9. Is it some sort of error? Someone explain this behavior please.
The value for that code is undefined. The compiler could be (and is allowed) to do all sorts of weird things like increment it twice at one point and not the other time, if it thinks that will make your program run faster. Never do anything like that in normal code.
In my opinion this code should always produce 10 using any compiler.

Here is how I think

step1: b = ++a + ++a + (a=2);
step1: b = ++a + (a=3) + (a=3);
step1: b = ++a + 6; //Sub-expression evaluated to 6
step1: b = (a=4) + 6;
step1: b =10;

Anyway as NT3 said do not use such code in real life
Last edited on
Topic archived. No new replies allowed.