Operator Precedence and Associativity
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 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
|Parenthesis (), Brackets ||1||Left to Right|
|++, --, unary minus (-), unary plus (+)||2||Right to Left|
|*, /, %||3||Left to Right|
|+, -||4||Left to Right|
|<,>, <=,>=||5||Left to Right|
|= =, !=||6||Left to Right|
|&&||7||Left to Right|
|||||8||Left to Right|
|Ternary ?:||9||Right to Left|
|=, +=, - =, *=, /=, %=||10||Right to Left|