As per my understanding the following sequence of steps take place when we do x = x++; where x has been initialised to some value before, say 5. Please correct if I am wrong.
Assuming x = 5, we do x = x++; 1. Original value of x is saved (say xOrig, so xOrig = 5) 2. x is incremented, so x = 6 3. xOrig is assigned to x, so x becomes 5 4. Therefore, for x = x++ will always equal original value.
But the above explanation doesnt hold true for x = ++x. So if x = 5 initially, then after x = ++x, x = 6
Can some one give a proper explanation for such postfix and prefix behaviour
With Love, Bonny
"Life is like an ice-cream, Enjoy it before it melts..."
If x is already initialised to be x=5, then the final result of both ++x and x++ will be x=6. The thing to notice when using prefix and postfix operators is the moment when (in this case), the addition is applied.
The best way to see this is with an example. Let's take
In this case, z will equal 8. And if we were to print out the value of x, it would be 6. However, if we alter the code slightly
The result would be that z would equal 9. and x would still equal 6.
So what is happening is that in the first code snipett, the value of x is being used, then after it has finished being used, it is incremented by 1, whereas in the second code snippet, the x is being incremented by 1 first, and then the value of z is calculated with the newly incremented x.
Where this may become confusing is when you see code such as
Don't let it fool you, it's result is the same. As there are no other operations that occur on that same line, all these are doing are incrementing x by 1.
Hope this helps.
[ June 20, 2006: Message edited by: Matt Gaunt ] [ June 20, 2006: Message edited by: Matt Gaunt ]
Your explanation holds true for x = ++x as well. Like this:
Assuming x = 5, we do x = ++x; Since it is prefix operator, x is incremented first and then its value is used in the expression. 1. x is incremented to 6 2. The value of x, which is now 6, is assigned to x.