Common precedence errors
What you'll learn: How to avoid logical bugs caused by assuming C evaluates math and comparisons in the order you read them.
The "Left-to-Right" Trap
When we read a sentence, we move from left to right. It is tempting to assume C does the same with code. However, C follows a strict hierarchy called precedence. If you forget this, you might write a line that looks perfectly logical but produces a completely different result than intended.
Think of it like a kitchen: if a recipe says "Boil water and chop onions," you can do both at once. But if it says "Toast bread and spread jam," the order is non-negotiable. In C, certain operators—like multiplication—always "happen" before others—like addition—regardless of which one appears first in the line.
Mixed Math and Logic
The most frequent errors occur when mixing arithmetic with comparisons or logic. For example, the "not" operator (!) and the "increment" operator (++) have very high precedence. They grab onto the nearest variable before the rest of the expression even gets a chance to breathe.
Look at this common mistake involving pointers and logic:
#include <stdio.h>
int main() {
int x = 10;
int y = 5;
int z = 20;
// ERROR: Logic vs Math
// You might want: Is x greater than (y + z)?
// But C sees: Is (x > y) then add z to the result?
// (10 > 5) is 1 (true). 1 + 20 = 21.
int result = x > y + z;
// ERROR: The "Not" trap
// You might want: If x is NOT equal to 10...
// But ! has higher precedence than ==.
// C sees: (!x) == 10. Since x is 10, !x is 0. 0 == 10 is false.
if (!x == 10) {
printf("This probably won't run.\n");
}
// FIX: Use parentheses to force your intent
int correct_result = x > (y + z); // Now it checks if 10 > 25
return 0;
}
The "Parentheses" Safety Net
Even professional developers cannot always remember the 15+ levels of C precedence. The most common error is being "too proud" to use parentheses.
In the example x > y + z, C calculates y + z first because addition outranks comparison. But if you meant to compare x and y first, the code fails silently. Using parentheses—(x > y) + z—tells the compiler (and other humans) exactly what you intended.
Key takeaway
When in doubt, wrap it in parentheses; never assume C reads from left to right.