Operator Precedence and Associativity

Operator Precedence

Operator precedence describes the order in which C evaluates different operators in a complex expression. For example, in the expression y=10+5*20, which happens first? Addition or Multiplication? Operator precedence tells us the execution order of different operator. Precedence level of different operator is shown in Table below, operators which are closest to top are executed first.

Therefore, in our example above, Multiplication is done before Addition because looking at Table multiplication operator has higher precedence than addition.

Operator Associativity

Operator associativity describes the order of execution of operators when they have same level of precedence. For example, in the expression y = 12* 20/5, which happens first? Multiplication or Division? Associativity can be either left to right or right to left. Associativity of different operator is shown in Table below.

Therefore, in our example above, Multiplication is done before Division because Multiplication and Division both have same precedence and have left to right associativity. So, evaluation starts from left i.e. first multiplication and then division.

Note: Associativity is used only when operators are of same precedence need to be evaluated.

Precedence and Associativity Table

OperatorPrecedenceAssociativity
Parenthesis (), Brackets []1Left to Right
++, --, unary minus (-), unary plus (+)2Right to Left
*, /, %3Left to Right
+, -4Left to Right
<,>, <=,>=5Left to Right
= =, !=6Left to Right
&&7Left to Right
||8Left to Right
Ternary ?:9Right to Left
=, +=, - =, *=, /=, %=10Right to Left