problem with unary operator ++

In the program below i expected the value of b to 8. But g++ is giving an output of 9. Can anyone explain me why is it behaving so?
1
2
3
4
5
6
7
8
9
10
#include<iostream>

using namespace std;

int main(){
  int a = 1,b;
  b = ++a + a++ + ++a;
  cout << a << " " << b << endl;
  return 0;
}
The C++ standard does not define what will happen when you modify the same variable in the same expression like that. The result could be anything.
In addition what Peter87 said.
Even with straightforward implementation: how should preincrements be handled? Order or argument calculation is unspecified, so program can:
a) do two preincrements first and then the rest of expression.
b) do first preincrement, get resulting value, do second preincrement when absolutely nedeed
c) do preincrements bur postpone writing value in memory until calculation is finished.
d) some other order.

Same can be said about postincrement. It is unspecified when real increment will take place. It can be after whole expression, it can be before both preincrements, it can be something else.

In straightforward compiler you can expect anything from 5 to 12. In optimising compiler you can easily get -42 as result


To modify value more than once between sequence points is illegal in C++. Do not do that.
Topic archived. No new replies allowed.