Variable Operators
Variable operators provide a convenient way to modify a variable's value based on its current value.
For example, instead of saying
accountBalance = accountBalance + deposit
you can say
accountBalance += deposit
which has the same effect.
Although variable operations are usually used as statements, they're actually expressions, which can be used within the context of larger expressions or statements. Except as noted, the result of a variable operation is the resultant value of the variable.
For example, this sequence of statements:
accountBalance += deposit; if (accountBalance > 500.00) Print('Checks may now be written for free.')
can be shortened (somewhat) to this:
if ((accountBalance += deposit) > 500.00) Print('Checks may now be written for free.')
Which form is better depends on your own taste and programming style.
Following is a complete list of the variable operators.
General Form | Affects the Variable's Value the Same Way As... | Remarks |
---|---|---|
variable += value | variable = variable + value | add (or concatenate) |
variable -= value | variable = variable - value | subtract |
variable *= value | variable = variable * value | multiply |
variable /= value | variable = variable / value | divide |
variable \= n | variable = variable \ n | floored integer divide |
variable %= n | variable = variable % n | modulo |
variable++ ++variable |
variable = variable + 1 |
increment Either of the two forms of ++ increases the variable's value by one. However, when this operation is used as an expression, each form produces a different result. For the form variable++, the result is the variable's original value, before it was incremented. For the form ++variable, the result is the variable's new value, after it's been incremented. |
variable-- --variable |
variable = variable - 1 |
decrement This works exactly the same as increment, except that the variable's value is decreased by one instead of increased by one. |
variable &= ord | variable = variable & ord | and |
variable |= ord | variable = variable | ord | or |
variable ^= ord | variable = variable ^ ord | exclusive or |
variable <<= n | variable = variable << n | shift left |
variable >>= n | variable = variable n | shift right |