0
What is happening here?
I saw this code in the challenge factory and I'm interested to hear it explained what happens: int main () { int x = 5; x = x++ + x-- + --x; cout << x; } The output is 15. I can't work out the order of precedence that the pre/postfix inc/decrement operators take here. Can someone explain it?
2 Antworten
+ 9
More then one unary operator is whenever used the question is become compiler dependent and different answer can be possible. Undefined behaviour is occupied due to this.
The answer is 15 may be according to this approach.
First x++ so due to post increment property first value used then incremented so
5 + x-- + --x
Now x is again used so previous post increment value become 6 so
5+ x-- + --x
Now due to post decrement the value of x become 6 then further use of x has documented value
5 + 6 + --x
Now value of x become 5 because of previous post decrement which is used in final unary operation
So due to that final pre decrement value of x become 4
5+6+4=15
So output came as 15.
0
Ok, so one way to describe it is that an inc/decrement operator will be evaluated once we move to a new term in the arithmetic. So if we have x++ + x-- once we move past the + sign, whatever is prior to it becomes evaluated.
this means we can achieve the same result by doing:
{
x = 5;
x++;
x += x--;
x -= --x;
}
which is breaking the arithmetic into separate lines.