I am not understanding the pre/post incrementing of this code example:
int1 = 14;
int2 = ++int1;
// Assert: int1 == 15 && int2 == 15
In this pre-incrementing example why does int1 == 15? Why is int1 incremented and not just int2?
Then we have:
int1 = 14;
int2 = int1++;
// Assert: int1 == 15 && int2 == 14
In this post-incrementing example why does int2 == 14? Why is int2 not incremented but int1 is?
Both
++int1andint1++incrementint1because that’s what the increment operators do: they increment their operand.The reason that
int2is 15 in the first example and 14 in the second example because the pre-increment and post-increment operators differ in their return value: The post-increment operator increments the operand, but returns the value that the operand had before being incremented. The pre-increment operator returns the new value of the operand.