If num starts at 0, then the assignment should be num = 0 then num should increment during the postfix incrementation of num!?
The increment happens before the assignment. Postfix increment does not mean that the increment happens after the current statement. It only means that the result of the expression will be the value of the variable before incrementing (as you can see in the quote of the specification posted by James).
Basically if you have foo(x++)
that's equivalent to oldX = x; x += 1; foo(oldX)
, not foo(x); x += 1;
. So x = x++;
is the same as oldX = x; x += 1; x = oldX
, not x = x; x += 1
.
I still feel like, you may have just copied someone elses work, posed as a professor, and want us to explain their code.
He already knows that replacing num = num++
with just num++
will fix the problem, so how would explaining why num = num++
doesn't work, help him take advantage of someone else's work?
When I write this in C++ I get 1
The C++ code invokes undefined behaviour. You might very well get different results on other implementations. If the behaviour were defined (i.e. if =
introduced a sequence point), you'd get 0 just like in Java.