The way I look at these pre/post increment/decrement operators is as follows. When you perform one of these, think of the compiler creating a new variable and: (a) copying the value, and (b) running the increment/decrement operation. The order of (a) and (b) changes depending on whether it's a post or pre operation.
So:
...would be equivalent to...
(I only included the {}'s to show that the temporary variable j goes immediately out of scope and doesn't exist outside the expansion that the compiler introduced...that's why you can't get at that temporary value and it just gets dropped out of existence.)
Now let's look at the expanded version of preincrement:
...is equivalent to...
If you always do those expansions in your head whenever you see the code, you can always figure out what's going on even in complicated operations like:
This looks really daunting at first, but if you know that the + operator is left associative (i.e. this statement will evaluate first at the rightmost +, and continue to crawl to the left), you can break it down step by step. And in this case, you see the effect of the temporary variable int this case because when it's returned, it doesn't simply go out of scope before getting used--it is that temporary variable that's used in place of the evaluated operand.
So
you should be able to see with a little consideration how the above code expands to:
Now you can easily expand the expressions for temp2 and temp3 as the rule above shows (we'll deal with temp1 after):
Now we have everything expanded except that first line, which I left till now because it has two of these little increment nasties. But it's not that bad, actually...you just make sure you expand the right most operand before the left:
Now if we put this whole mess together, this:
expands to this:
And now a final runthrough to see what x and k end up as. I'll put a comment after each line whenever a value changes:
Fascinating, no? (Well, maybe not.)
sev
[ February 29, 2004: Message edited by: sever oon ]