Compound multiplication and division
What you'll learn: How to use shorthand operators to multiply or divide a variable by a value and save the result in one step.
The Shortcut for Growth and Decay
In C programming, you frequently need to update a variable based on its current value. Imagine you are writing code for a video game where a player picks up a "Double Damage" power-up. You need to take the current attackPower, multiply it by 2, and then save that new total back into attackPower.
Usually, you would write it like this:
attackPower = attackPower * 2;
While this works perfectly, C offers a "compound assignment" shortcut to keep your code lean: *=. Similarly, if you want to cut a value in half (perhaps an enemy's health is halved by a spell), you can use /=. These operators tell the computer: "Take the value currently in this box, perform the math, and put the result back into the same box."
How it Looks in Code
Think of these operators as a combined "math + update" command. Instead of mentioning the variable name twice, you mention it once, followed by the compound operator.
#include <stdio.h>
int main() {
int gold = 50;
int potions = 20;
// Compound Multiplication: Double the gold
// Equivalent to: gold = gold * 2;
gold *= 2;
// Compound Division: Use half the potions
// Equivalent to: potions = potions / 2;
potions /= 2;
printf("Gold: %d\n", gold); // Output: 100
printf("Potions: %d\n", potions); // Output: 10
return 0;
}
Why Use Them?
You might wonder why we bother with shortcuts. Using *= and /= serves two main purposes:
- Readability: When variables have long names, like
playerInventorySpaceRemaining, repeating the name on both sides of the equals sign makes the line cluttered. The compound operator makes your intent clear immediately. - Safety: It prevents typos. If you have to type a complex variable name twice, you might accidentally mistype one of them, creating a bug. With compound operators, you only type the name once.
Remember that division in C follows the standard rules: if you divide two integers using /=, the result will be truncated (the decimal part is chopped off). If you need precision, use float or double variables.
Key takeaway
The *= and /= operators provide a concise way to multiply or divide a variable by a value and update the original variable instantly.