Operators precedence in C
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.
Operator precedence in C
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)).
Operator Associativity in C
Associativity comes into picture when we have operators of the 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 decrement||Left-to-right|
|.||Structure and union member access|
|->||Structure and union member access through pointer|
|2||++ —||Prefix increment and decrement||Right-to-left|
|+ –||Unary plus and minus|
|! ~||Logical NOT and bitwise NOT|
|3||* / %||Multiplication, division, and remainder||Left-to-right|
|+ –||Addition and subtraction|
|4||<< >>||Bitwise left shift and right shift|
|5||< <=||For relational operators < and ≤ respectively||Left-to-right|
|> >=||For relational operators > and ≥ respectively|
|== !=||For relational = and ≠ respectively|
|^||Bitwise XOR (exclusive or)|
||||Bitwise OR (inclusive or)|
|7||&&||Logical AND||Left to right|
|+= -=||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|