int a = 1;
a += ++a;
cout << a << endl; // 4
int a = 1;
a += a++;
cout << a << endl; // 3
why these two exmaples have difference behaviour?
int a = 1;
a += ++a;
cout << a << endl; // 4
int a = 1;
a += a++;
cout << a << endl; // 3
why these two exmaples have difference behaviour?
Warning: the assignments you are looking at have undefined behaviour. See Why are these constructs using pre and post-increment undefined behavior? Also this answer in the question Undefined behavior and sequence points addresses how C++17 resolves these issues.
It is possible that your compiler processes the operations in the following way, explaining the differences:
pre-increment operation: The following lines:
a=2;
a+=++a;
are equivalent too:
a=2;
tmp=++a;
a+=tmp;
which reads as:
2
to the variable a
a
(++a
) giving a
the value 3
and assign it to tmp
(making it 3
)a
(currently 3
) with the value of tmp
(currently 3
) giving us 6
post-increment operation: The following lines:
a=2;
a+=a++;
are equivalent too:
a=2;
tmp=a++;
a+=tmp;
which reads as:
2
to the variable a
a
(a++
) first returns the original value of a
(i.e. 2
) and assigns it to tmp
(making it 2
) and then increments a
to the value of 3
a
(currently 3
) with the value of tmp
(currently 2
) giving us 5
a++
and ++a
do different things.
a++
increases a
by 1 and returns previous value .
++a
increases a
by 1 and returns new value.
a++
returns the value of a
before the increment. ++a
returns the value of a
after the increment.
That is why they are different.
The difference here is not the priority of the three operators. It follows this chart where a++
> ++a
> a+=
.
But rather the way the two increment operators work. When you use the ++a
you first increment and then return that value (the new one.) Where as using a++
will first use the old value and then increment. Also see here for related.
a += ++a;
Replaced with compiler like below :
a = a + 1;// a = 1 + 1
a = a + a;// a = 2 + 2
In second example
a += a++;
is resolved as below :
a = a + a;// a = 1 + 1
a = a + 1;// a = 2 + 1
Below are the rules for operation: https://en.cppreference.com/w/cpp/atomic/atomic/operator_arith2 https://en.cppreference.com/w/cpp/language/operator_precedence
With:
a += a++;
you add the previous value of a, and then increment a by 1
With:
a += ++a;
You add the value already incremented by 1 of a