+ 1
Why does this not execute?
I was playing around on play mode a couple times, and stumbled upon a question that looks like this: int x = 0; x = x++; cout << ++x; The output is 1, because of the ++x. But why isn't the x++ executing? I would've thought x would set itself to x, then x would increment; why isn't that happening? I notice that if I replace x++ with ++x then the output is indeed 2, which leads me to believe that x++ is not executing. Any help is appreciated. Thanks.
3 Answers
+ 3
x++ is equivalent to x = x + 1, so you never need to write x = x++.
If I had to take a guess, I would say that in c++, x = x++ leads to:
1: the expression x++ to be evaluated first (value: 0)
2: x incremented by 1 via x++ (x=1)
3: x receiving the value evaluated earlier via x= (x=0)
Hence how x = x++ does nothing.
+ 2
In the assignment x = x++ you first extract the old value of x to use in evaluating the right-hand side expression, in this case 'x'; then, you increment x by 1. Last, you assign the results of the expression evaluation (0) to x via the assignment statement.
+ 1
Thanks guysđ
Of course I personally wouldn't use anything like the statement in this question, as it just causes unnecessary confusion; but that is how the question was in play mode, haha.
I find it odd that it would be using the previous value of x rather than the new one, but I guess it is what it is.
Thanks again.



