Precedence of * over +
What you'll learn: How C decides the order of calculations when multiplication and addition appear in the same line of code.
In daily life, we follow certain protocols to keep order. If you are putting on socks and shoes, the "precedence" is clear: socks first, then shoes. If you do it in reverse, you get a very uncomfortable mess. C programming has similar protocols for math, ensuring that every computer in the world calculates the same result for the same equation.
The Mathematical Hierarchy
When you write a line of code like int result = 5 + 2 * 10;, C doesn't just read from left to right like a book. If it did, it would calculate 5 + 2 (7) and then multiply by 10 to get 70.
Instead, C follows the rules of Operator Precedence. In this hierarchy, multiplication (*) has a higher priority than addition (+). Think of multiplication as an "express lane" at the grocery store—it gets processed before the standard lanes. In our example, C looks at the line, sees the multiplication, and handles 2 * 10 first. Only after that result (20) is found does it add the 5. The final answer is 25.
Seeing it in Code
Here is how this looks in a functional snippet of C. Notice how the placement of the numbers doesn't change the priority of the operators.
#include <stdio.h>
int main() {
// Multiplication happens first, regardless of position
int method_one = 10 + 5 * 2; // 5 * 2 is 10, then + 10 = 20
int method_two = 5 * 2 + 10; // 5 * 2 is 10, then + 10 = 20
printf("Result 1: %d\n", method_one);
printf("Result 2: %d\n", method_two);
return 0;
}
Why This Matters
If you are calculating a total price for three shirts plus a shipping fee, you would write total = shipping + 3 * shirt_price. Because * has higher precedence, C correctly calculates the cost of the shirts before adding the shipping. If addition came first, you would accidentally multiply the shipping fee by three as well!
By internalizing that * is "stronger" than +, you can write complex formulas without worrying that the computer will misinterpret your intent.
Key takeaway
C performs multiplication before addition because * has higher precedence than +.