Miscellaneous unary operators: these are prefix and postfix increment (++
), prefix and postfix decrement (--
), unary plus (+
) and unary minus (-
). Here are examples:
a++; ++a; a--; --a; +a; b = -a; b = 2 * a++; b = 2 * ++a;
The unary minus is easiest to understand; it simply makes a negative number positive and vice versa. All the rest are really as valuable for their side effects as much as for their main effect. Unary plus, for example, won't change the sign of a Number (unary minus does that) or its value, so you might think it's useless. Nevertheless, it does force any variable it's used with to undergo type conversion (discussed later), and on rare occasions that can be useful. The pre/post increment/decrement operators just give you a fast way of saying 'a = a + 1' or 'a = a—1'—they increase or decrease the variable they're applied to by one, which is a common operation. Care has to be taken if they are mixed with other operators in an expression, or used in an assignment, as this example shows:
a = 5; c = a++ + 2; // c = 7, not 8;
b = 10; c = ++b + 2; // c = 13, not 12;
a = 6; b = 11; c = ( ++a == b++ )// not obvious (but c is false as 7 == 11 is false)
When the ++
is placed before the variable it works on, that variable is incremented, and the new value is used in any expression it's part of. However, if the ++
is placed after the variable it works on, the variable's old value (before increment) is used in the expression and then after that's over, the increment is applied as an afterthought. As the last statement in the example shows, it can get confusing if overused.