Decrement, pre- or post- '--'

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

Y := --X + 2

The above shows the pre-decrement form; it means "decrement before providing the value for the next operation". It decrements 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 4 in X, then the expression, 4 + 2 is evaluated, finally writing the result, 6, into Y. After this statement, X equals 4 and Y equals 6.

Y := X-- + 2

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

Since Decrement 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 4, then 4 + 4 is evaluated and Y is set to 8.

Y := X-- + X

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

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