Wednesday, February 3, 2016

C Operator Precedence and Associativity Table with Examples

Operator Precedence
It usually means, if an expression has multiple operators in it, which operator get the precedence over others. To understand what's meant by operator precedence, let's take an arithmetic expression as an example.

Consider, int a = 2 + 3 * 4. Value of 'a' would be 14, not 20. This is because operator '*' is executed before '+', like the BODMAS rule. So we can say that operator '*' has precedence over operator '+' and the expression would be grouped as int a = (2 + (3 * 4)).

Operator Associativity

Associativity specifies how the operators are grouped for evaluation. For example, consider the expression 2 + 3 + 4Note: In this case (+ operator), the result of different grouping doesn't matter. But that might not be the case with other operators.

can you tell how the expression will be grouped? ((2 + 3) + 4) or (2 + (3 + 4)). This is determined by the associativity of operators. From the above example we can understand that, associativity comes into picture only when expression has operators of same precedence.

Different Types of Operator Associativity

There are two types of associativity possible known as 'Right to Left' associativity and 'Left to Right' associativity. L->R (left to right) associativity means operator on the left hand side will get priority over right hand operator and R->L (right to left) associativity means right most operators will get more priority. To understand the associativity in detail, lets consider two example expressions.
  1. a = b = c : '=' has right to left associativity. So the expression will be grouped as (a = (b = c))
  2. a + b + c : '+' has left to right associativity. So the expression will be grouped as ((a + b) + c)


No comments: