|
||||||
|
Relate Components | RelateScript | BlueStep.js |
Increment and Decrement Operators
The increment and decrement operators work on Integer or Float variables and fields. Each operator causes the number stored to either increase or decrease by 1. Pre-increment: ++x Pre-decrement: --x Post-increment: x++ Post-decrement: x-- Examples: x = 1; What are the values of a, b, c, d and e? Let's go through this one line at a time. At the beginning of the second line, x is equal to 1. According to order-of-operations the post-increment operation happens first so 1 is added to x and the value of x prior to the increment is used as the first value in the subtraction. Next the subtraction occurs, but since x is already incremented, we are actually subracting 2 from 1. The result of -1 is then assigned to the variable a. In the next line x is once again incremented by 1, but this time the value of x after the increment is used in the subtraction. As before the new value of x is also used on the right side of the subtraction, so 3 minus 3 is assigned to the variable b. In the fourth line things get really weird. You might think that since the increment has highest precedence that adding one to x is the very first thing that happens. This is not actually the case. The first thing that happens is the value of x is retrieved as the left value of the minus operation. The value retrieved is, of course, 3. Then the minus operation retrieves its right value and the increment, having precedence, occurs with the result being 4. So c is assigned 3 minus 4. The fifth line works like the fourth, except the value of x prior to the increment is used in the minus operation, so d is assigned 4 minus 4. And x is now equal to 5. The final line is not valid and will result in an error when it is written. This is because the result of ++x is the value of x after the increment, not x itself. The value of x is an Integer, but x is a variable of type Integer. The error results because you can add 1 to x and assign it back into x with a result of 6, but you cannot add 1 to 6 then assign it back to 6. The addition could work, but the assignment is impossible. |