Razvan wrote:
> step 1: evaluate left operand (a == 2 )
> step 2: evaluate right operand (a++ which also gives 2)
> step 3: evaluate a = 2 + 2; => a == 4
> step 4: increment a (don't forget about the post increment operator)
> => a== 5
Revise that as follows:
> step 1: evaluate left operand (a == 2)
> step 2a: evaluate right operand (a++ which also gives 2)
> step 2b: as a side effect of step 2, increment a (a == 3)
> step 3: add the left and right operands (2 + 2 = 4, a still == 3)
> step 4: assign the result to a (a == 4)
So the change made to a in step 2b is overwritten in step 4. The
important thing to note is that step three adds the previously computed
results of the expressions 'a' and 'a++', NOT the current value of the
'a' variable. (Also note that steps 2a and 2b are not strictly
sequential; that's just a model for the predicted outcome.)
Here are a few other expressions to think about and check your
understanding:
a = (a++) + a;
a = a * (a++);
a = (a++) * a;
> Could it be because the operator is applied
> BEFORE the final operation a = 2 + 2 ? That means there is an
> intermediate value of 3 that is overwritten with 4 when a= 2 + 2 ?
> Is this a good explanation ?
Yes., that's a perfect explanation. The increment happens at the same
time the post-increment expression is evaluated, which is *before* the
assignment is evaluated. The post-increment (versus pre-increment) only
changes the RESULT of the expression; it makes no difference as to when
'a' is incremented. Unfortunately, the operator names confuse people a
bit.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation