Whats happening x after executing the code below;
int x = 10;
x += x--;
I'm expecting result 19 (adding x to x and then decrease x by 1) but result 20. How does it works behind the curtains? Thank your for your answers.
Whats happening x after executing the code below;
int x = 10;
x += x--;
I'm expecting result 19 (adding x to x and then decrease x by 1) but result 20. How does it works behind the curtains? Thank your for your answers.
The behavior in this case was undefined before C++17, see e.g., https://en.cppreference.com/w/cpp/language/eval_order#Undefined_behavior , so if your compiler does not conform to it, it is no use testing or trying to understand it: it will depend on implementation, or even version of the compiler.
If your compiler conforms to C++17, it is guaranteed that in a simple or compound assignment (=
or e.g. +=
, respectively) all of the side effects of right hand side will be dealt with before evaluating the left hand side.
In your case, x--
is evaluated to be 10
accompanied by setting x=9
as its side effect, then the computer will add 10
to x=9
resulting in x=19
.
Thanks to Michał for his correction, which I incorporated into the answer.
Having an older c++ might probably not do the job as the behaviour is literally defined to be undefined, by the older standard. (Thanks to @LightnessRacesinOrbit)
If you just try out an online compiler which will have the latest version, it works just fine and the result is 19 as you expected (x+=x--
is the same as x= x+x--
. This means for getting the new "x", it has to sum the old "x"+the old "x" -1. So it will do x+(x--)
, which is x=10+(9)
.
Try it out here: with:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
x += x--;
cout<<x<<endl;
}