Chained assignments a = b = c
What you'll learn: How to save time by setting multiple variables to the same value in a single line of code.
The bucket brigade
Imagine you have three empty buckets labeled a, b, and c. You want to fill all of them with exactly five gallons of water. You could fill a first, then b, then c separately. In C, that would look like three separate lines of code.
However, C allows a shortcut called chained assignment. Instead of three trips to the well, you can line the buckets up and let the water flow from one to the next in a single motion: a = b = c = 5;.
How it works: Right-to-Left
To understand why this works, you have to look at the "direction" of the equals sign. In C, the assignment operator (=) has right-to-left associativity. This is a fancy way of saying the computer starts at the far right of the line and works its way back to the left.
In the expression a = b = 5;, the computer doesn't look at a first. It looks at the very end:
- It sees
b = 5. It performs this action, putting the value5into the variableb. - Crucially, in C, an assignment itself has a "result"—the value that was just assigned. So, the expression
b = 5actually "results" in the value5. - The computer then moves left and sees
a = (the result of the previous step). Since the previous step resulted in5, it assigns5toa.
Seeing it in code
This technique is most common when you are initializing several variables to zero or a starting constant at the beginning of a program.
#include <stdio.h>
int main() {
int gold_medals;
int silver_medals;
int bronze_medals;
// Reset all scores to zero at once
gold_medals = silver_medals = bronze_medals = 0;
printf("Gold: %d, Silver: %d, Bronze: %d", gold_medals, silver_medals, bronze_medals);
return 0;
}
When to use it
Chained assignments are great for readability when the variables are logically related (like the medals in the example above). However, avoid chaining assignments that aren't related, as it can make your code harder to scan. If you are setting the player_age and the gravity_constant, keep them on separate lines!
Key takeaway
Chained assignments evaluate from right to left, passing a single value down a chain of variables.