Increment, pre- or post- '++'

The Increment operator is a special, immediate operator that increments a variable by one and assigns the new value to that same variable. It can only be used in run-time variable expressions. Increment has two forms, pre-increment and post-increment, depending on which side of the variable it appears on. The pre-increment form appears to the left of a variable and the post-increment form appears to the right of a variable. This is extremely useful in programming since there are many situations that call for the incrementing of a variable right before or right after the use of that variable's value. For example:

Y := ++X - 4

The above shows the pre-increment form; it means "increment before providing the value for the next operation". It increments the value of X by one, writes that result to X and provides that result to the rest of the expression. If X started out as 5 in this example, ++X would store 6 in X, then the expression, 6 - 4 is evaluated, finally writing the result, 2, into Y. After this statement, X equals 6 and Y equals 2.

Y := X++ - 4

The above shows the post-increment form; it means "increment after providing the value for the next operation". It provides the current value of X for the next operation in the expression, then increments the value of X by one and writes that result to X. If X started out as 5 in this example, X++ would provide the current value for the expression (5 - 4) to be evaluated later, then would store 6 in X. The expression 5 - 4 is then evaluated and the result, 1, is stored into Y. After this statement, X equals 6 and Y equals 1.

Since Increment is always an assignment operator, the rules of Intermediate Assignments apply here. Assume X started out as 5 for the following examples.

Y := ++X + X

Here, X would first be set to 6, then 6 + 6 is evaluated and Y is set to 12.

Y := X++ + X

Here, X's current value, 5, is saved for the next operation (the Add) and X itself is incremented to 6, then 5 + 6 is evaluated and Y is set to 11.

Unless otherwise noted, content on this site is licensed under the
Creative Commons Attribution-ShareAlike 4.0 International License.