Operator Precedence And Associativity

Lesson 2.4: Operator Precedence and Associativity


In C, when you have multiple operators in an expression, it's crucial to understand the order in which they are evaluated. This order is determined by two concepts:


1. Operator Precedence (Priority)


What It Is: Operator precedence defines which operators are evaluated first when there are multiple operators in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

The C Precedence Table: You don't need to memorize the entire table, but it's helpful to be familiar with the general order:

Precedence (High to Low) Operators

Highest () (Parentheses)

[] (Array subscripting), . (Structure member), -> (Pointer to structure member)

++ (Post-increment), -- (Post-decrement)

+ (Unary plus), - (Unary minus), ! (Logical NOT), ~ (Bitwise NOT)

* (Multiplication), / (Division), % (Modulus)

+ (Addition), - (Subtraction)

<< (Left shift), >> (Right shift)

<, >, <=, >= (Relational)

==, != (Equality)

& (Bitwise AND)

^ (Bitwise XOR)

&& (Logical AND)

?: (Conditional/Ternary)

Lowest = (Assignment), +=, -=, *=, /=, %=, etc. (Compound assignment)

Example:


C

int result = 5 + 3 * 2;  // result will be 11, not 16

// Multiplication (*) has higher precedence than addition (+)


2. Operator Associativity (Direction)


What It Is: When two or more operators with the same precedence appear in an expression, associativity determines the order in which they are evaluated.

Left-to-Right Associativity: Most operators in C are left-associative, meaning they are evaluated from left to right.

Right-to-Left Associativity: A few operators (e.g., assignment =, unary operators) are right-associative, meaning they are evaluated from right to left.

Example:


C

int x = 5;

x = x + 3;  // Left-to-right associativity

int y = 10;

int z = y = x;  // Right-to-left associativity (x is assigned to y, then y is assigned to z)


Overriding Precedence with Parentheses


You can use parentheses () to override the default precedence and associativity rules. Expressions within parentheses are always evaluated first.


C

int result = (5 + 3) * 2;  // result will be 16

Key Points


Understanding Precedence and Associativity: Knowing these rules helps you write correct and predictable C code.

Use Parentheses for Clarity: Even when not strictly needed, parentheses can make your code more readable by clarifying the order of operations.

The C Precedence Table: Refer to this table when in doubt, but remember that common sense and good coding practices often guide you in the right direction.

Let me know if you have any other questions.

Course Syllabus