I was reading a separate post with postfix operators and have some confusion on the evaluation of postfix operators. For example:
This will print out j=0. I understand why this occurs as the value of j is incremented AFTER the assignment occurs. Now consider the next piece of code:
This will print out j=1. In this case the increment has occurred BEFORE the assignment occurs.
Can it be said that when there are more operations than just a single postfix operator that the postfix will be applied to the variable and a left to right evaluation occurs? (Example: the above statement j = j++ + j turns into: j = (j + 1) + 0 j = 1 + 0 Thus: j=1
This is all about evaluation of operands. Let me explain exactly what is happening and you can draw your own conclusions.
Here's our line of code:
In order to evaluate this expression, we must first evaluate operands, from left to right. The first operand we evaluate is j++. As you already know, this operand evaluates to 0 but, as a side-effect, j is incremented to 1. We now have this:
Now, we evaluate the next operand, which is just j. At this point, j is 1 so our expression evaluates to this:
Obviously, that expression assigns the value of 1 to j.
Thanks. I like the method you use to break out the values (tracking the value of the variable as a comment on the right side of the expression) as the order is extremely important. I changed the example slightly and got different results which only made sense once I used your method of tracking the value. For example: