Course contentsShow
← C
Lesson 212 of 1,2193. Operators and ExpressionsFree lesson

Operator precedence table

Operator precedence table

What you'll learn: How C uses a built-in ranking system to decide which parts of a math or logic expression to calculate first.

The "Order of Operations" for C

In elementary school, you likely learned PEMDAS—the rule that says you must do multiplication before addition. C follows a similar, but much larger, set of rules called the Operator Precedence Table.

Think of this table as a "VIP list" for symbols. When C looks at a line of code with multiple operators, it doesn't just read left-to-right. Instead, it scans the line, finds the operator with the highest "rank," and executes that first. Without these rules, a single line of code could produce different results depending on how the computer felt that day!

How the hierarchy works

Imagine you are at a crowded airport. Travelers with "First Class" tickets board before those with "Economy" tickets, even if the economy passengers were standing at the gate first.

In C, math operators like * (multiplication) and / (division) are "First Class." They have higher precedence than + and -.

#include <stdio.h>

int main() {
    int result;

    // Even though 10 + 5 comes first, the 5 * 2 happens first.
    // 10 + (5 * 2) = 20
    result = 10 + 5 * 2; 

    // Using parentheses changes the "rank" manually.
    // (10 + 5) * 2 = 30
    result = (10 + 5) * 2;

    return 0;
}

Reading the table

The official C precedence table has about 15 levels. At the very top (highest priority) are parentheses () and the member access operators. Near the middle are the arithmetic operators you use for math. Toward the bottom are comparison operators like > (greater than) and == (equal to), and at the very bottom is the assignment operator =.

This is why, in the line x = 5 + 2;, the computer calculates 5 + 2 first and then performs the assignment. If = had higher precedence than +, the code wouldn't make any sense!

Associativity: The tie-breaker

What happens if two operators have the same rank, like 10 / 2 * 5? This is where associativity comes in. Most operators in C are "Left-to-Right," meaning if the ranks are equal, C just processes them like a sentence. However, some (like the = sign) are "Right-to-Left."

Key takeaway

Operator precedence is a ranking system that determines the order of execution; when in doubt, use parentheses () to force the order you want.