Precedence of assignment
What you'll learn: Why the assignment operator = is usually the last player to take its turn in an expression.
The "Grand Finale" Operator
In the world of C programming, operators have a specific hierarchy called precedence. You might remember from math class that multiplication happens before addition. In C, the assignment operator (=) sits near the very bottom of this hierarchy.
Think of an expression like a theatrical play. The addition, subtraction, and multiplication operators are the actors performing the scenes. The assignment operator is the cleaning crew that comes in only after the play is finished to pack everything away into a box (the variable).
Because assignment has very low precedence, C calculates everything on the right side of the = sign before it tries to store that value in the variable on the left.
Seeing it in action
If assignment had high precedence, code would be a nightmare to read. We would need parentheses around every single math problem just to make sure the result got saved correctly. Thankfully, C handles the heavy lifting first.
#include <stdio.h>
int main() {
int result;
// Precedence at work:
// 1. 10 * 2 is calculated (20)
// 2. 20 + 5 is calculated (25)
// 3. ONLY THEN is 25 assigned to 'result'
result = 10 * 2 + 5;
printf("The result is: %d", result);
return 0;
}
In the example above, C doesn't look at result = 10 and stop there. It treats the entire right-hand side as one big task. It performs the multiplication, then the addition, and only when it has a final single number does it perform the "assignment" action.
Why this matters
The most common mistake involving assignment precedence happens when you try to combine assignment with logic, such as in if statements. Because = is so low on the list, almost any other symbol—like +, <, or ==—will beat it in a race.
If you want an assignment to happen before something else, you must wrap the assignment in parentheses to force C's hand. Otherwise, the "cleaning crew" will patiently wait until every other calculation is complete before doing its job.
Key takeaway
The assignment operator has very low precedence, ensuring all calculations on the right are finished before a value is stored in the variable.