Compound Assignment Operators
A compound assignment operator combines a variable's current value with another value and stores the result back in the variable. A coffee company uses them to track its beans, in grams.
Adding and subtracting
int beans = 2000;
beans -= 90;
beans += 1000;
Five espresso shots of 18 grams each use 90 grams, and the statement
beans -= 90; takes them off. It does the same thing as beans = beans - 90;: it subtracts 90 from the value beans holds and stores the result, 1910, back in beans. Then a delivery adds 1000 grams, and beans holds 2910.Each statement starts from what the one before it stored. The
+= adds 1000 to 1910, not to the 2000 in the declaration.The whole right side
The company has 6 shops, and 1 is closed this week. The beans are split evenly among the shops that are open.
int shops = 6;
int closed = 1;
beans /= shops - closed;
The value on the right is the whole expression
shops - closed, which is 5. So the statement means beans = beans / (shops - closed);, with parentheses that were never typed, and beans gets 2910 / 5, which is 582.Expanded without those parentheses, it would be
beans = beans / shops - closed;. Precedence makes that 2910 / 6 - 1, which is 484, so the parentheses can't be dropped.Remainder and multiplication
The 582 grams are packed into 250-gram bags, and the program keeps what doesn't fill a bag.
beans %= 250;
Two bags take 500 grams, and 582 % 250 is 82, so
beans holds 82.The operators work on
double variables too. A cup of coffee costs 4.0 dollars, and the price goes up by a quarter.double price = 4.0;
price *= 1.25;
The variable
price now holds 5.0. Since price is a double, a /= on it would keep the fraction that an int division drops.Adding or subtracting one
One shop counts the shots it pulls.
int shots = 41;
shots++;
shots--;
The increment operator
++ adds 1 to the value stored in shots and stores the new value, 42. The decrement operator -- then subtracts 1 and stores 41. In this course each one is written after the variable, on a line by itself as a complete statement.