Sunday, December 10, 2017

Postfix increment/decrement operator explained

This operator has caused many concept problems for programming beginners.
This is more difficult and troublesome than prefix counterpart, because the prefix always carry the increment/decrement first. However, for postfix version the operation is "delayed".
Problems arise when this operator is 'misused' to construct logically difficult statements (they tend to appear on computer science exams, unfortunately)


Example 1.
Notice the absurdity to construct the following statement:
//[Java]
int i = 10;
i += i++;
System.out.println(i);

What is the output?
. . .
Running the code shows that output is 20. Why?

Let's look through the code.
1. A variable named i is created and immediately assigned a value of 10.
2. According to order of precedence, i++ gets evaluated first, i.e. i += (i++);. i++ returns i in the course of current statement. Now it becomes i += (i); which is the shorthand notation for i = i + (i); Finally, i is assigned with value 20 (10+10).
3. IMPORTANT. The assignment to i overwrites the value changed with increment operator, and all references to i are in pre-increment value (postfix).
4. Therefore, the pending increment of i is lost with its assignment

Example 2.
//[Java]
int i = 2, j;
j = i++ * i++ * i++;
System.out.println("i = "+i + ", j = "+j);

What is the output?
Running code show output is i = 5, j = 24. Why?

1. There is no conflicting assignment for i, so all postfix pending increment will carry out as usual
2. In same statement, each next reference of i will apply pending increment of current postfix reference of i. So j = (2) * (3) * (4)
3. At end of assignment to j, the final pending increment is applied to i, so i = 5.