Order of evaluation vs Precedence
What you'll learn: Why operator precedence only tells you how to group operations, not the chronological order in which the computer calculates them.
The Sandwich Analogy
Imagine you are making a sandwich. Precedence is like the recipe: it tells you that the cheese must go inside the bread. It defines the structure. However, the recipe doesn’t care if you slice the tomatoes first or open the mayo jar first. That is the order of evaluation.
In C, beginners often confuse these two concepts. They assume that because * has higher precedence than +, the computer must calculate everything related to the multiplication before even looking at the addition. This is a dangerous myth.
Structure vs. Timing
Precedence only determines which operands belong to which operators. In the expression a + b * c, precedence tells the compiler: "Group b and c together for multiplication, then add the result to a." It defines the mathematical grouping, not the timing.
The C standard gives the compiler a lot of freedom to be efficient. In many cases, the compiler can decide to evaluate a before it even touches b or c.
#include <stdio.h>
int main() {
int x = 5;
// Precedence says: (x++) * (x++)
// But WHICH (x++) happens first? The C standard doesn't say!
int result = (x++) + (x++);
// Warning: This behavior is "undefined."
// On one computer, result might be 11. On another, 10.
printf("%d", result);
return 0;
}
Why This Matters
When your expressions have side effects (like ++ or a function that prints to the screen), the order of evaluation becomes critical.
If you write draw_circle() + draw_square(), precedence says you must add their results. However, C does not guarantee which shape is drawn on the screen first. If your program depends on the circle appearing before the square, relying on precedence will eventually cause your code to crash or behave strangely when moved to a different computer.
To stay safe, keep your expressions simple. If the timing matters, split the expression into two separate lines.
Key takeaway
Precedence determines how terms are grouped (the "who"), but the order of evaluation determines the timing of the calculations (the "when").