September 04, 2002

The ++ operator

Someone asked, so I posted the answer here as well:

In a loop, it doesn't really matter whether the increment operator "++"
comes before the variable or after the variable. However, there is a subtle
difference in other situations. If the ++ operator is before a variable,
then the expression "a + 1" is evaluated before the variable's value is
assigned. If the ++ operator is after a variable, then the express "a + 1"
is evaluated after the variable's value is assigned. Check out the example
below to see the different results of positioning the "++" operator before
and after a variable.

-----------------------------------------
a = 1;
b = ++a;
trace("a = " + a + ", b = " + b);
RESULT OUTPUT: "a = 2, b = 2"

a = 1;
b = a++;
trace("a = " + a + ", b = " + b);
RESULT OUTPUT: "a = 2, b = 1"
------------------------------------------

In the first case, the variable "b" receives the value of "a" only after the
expression "a = a + 1" has been evaluated. Thus, b = a + 1.

In the second case, the variable "b" receives the value of "a" before the
expression "a = a + 1" can be evaluated. Therefore, b = a, and then a = a +
1.

This behavior also occurs for other assignment operators, such as /= (divide by), *= (multiply by), and -- (decrement by 1).

-Sam

Posted by samuel at September 4, 2002 08:57 PM