Operator precedence and associativity is a very important aspect of programming as it is essential to know while coding, which operator will be taken first for evaluation as accordingly the results will vary. As we have BODMAS rule in mathematics, similarly we have operator precedence and associativity in C.

  1. Operator precedence means the order in which an operator in an expression will be evaluated.

For instance : 10*5-2 = ?  Here since multiplication operator has higher precedence hence it will be evaluated first and the answer would be 48 ((10*5)-2 )and not 30 (10*(5-2)).

  1. Associativity comes into picture when we have operators of same precedence in an expression.  It lets us know in which direction we need to start our evaluation, from left to right or right to left.

For instance: 10/5*2 = ? Here, division and multiplication have same precedence. However since operands have left to right associativity, that is starting from left we move towards right evaluating. Hence, the answer is 4 ((10*5)/2) and not 1 (10/(5*2)).

1++ —Suffix/postfix increment and decrementLeft-to-right
()Function call
[]Array subscripting
.Structure and union member access
->Structure and union member access through pointer
(type){list}Compound literal
2++ —Prefix increment and decrementRight-to-left
+ –Unary plus and minus
! ~Logical NOT and bitwise NOT
(type)Type cast
*Indirection (dereference)
_AlignofAlignment requirement
3* / %Multiplication, division, and remainderLeft-to-right
+ –Addition and subtraction
4<< >>Bitwise left shift and right shift
5< <=For relational operators < and ≤ respectivelyLeft-to-right
> >=For relational operators > and ≥ respectively
== !=For relational = and ≠ respectively
6&Bitwise ANDLeft-to-right
^Bitwise XOR (exclusive or)
|Bitwise OR (inclusive or)
7&&Logical ANDLeft to right
7||Logical OR 
8?:Ternary conditionalRight-to-Left
9=Simple assignmentRight-to-Left
+= -=Assignment by sum and difference
*= /= %=Assignment by product, quotient, and remainder
<<= >>=Assignment by bitwise left shift and right shift
&= ^= |=Assignment by bitwise AND, XOR, and OR

Report Error/ Suggestion

Related Posts:


CopyRight © 2019

CopyRight © 2019