We have already seen a few simple examples of assignment operators when we looked at assigning values to variables when we first define them. The same assignment operator works for assigning a replacement value to a variable. Here are some examples.
1 var price = cost + profit;
2 remains = purchased - eaten;
3 min = count++;
In 1 a new variable price is created. The values in cost and profit are added together and the result of this addition is stored in price. The values in cost and profit are not changed.
2 subtracts eaten from purchased and stores the result in remains.
3 copies the value from count into min. It then adds one to count so that count will be one greater than min after this statement runs.
fruit += apples;
price -= tax;
timeWorked *= days;
pages /= books;
entry %= selection;
The first of these statements has the same result as if we had put fruit = fruit + apples; The difference is that instead of adding fruit and apples together in a temporary field and then moving the result back into fruit the value of apples can be added to fruit directly.
Similarly price -= tax; is equivalent but more efficient than price = price - tax;, timeWorked *= days; is equivalent to timeWorked = timeWorked * days; and so on.
This article written by Stephen Chapman, Felgall Pty Ltd.