C

C

An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulation. C language supports a rich set of built in operators.

Type of Operators

C operators can be classified into below following types.

- Arithmetic Operators
- Relational Operators
- Shift Operators
- Logical Operators
- Bitwise Operators
- Ternary or Conditional Operators
- Assignment Operator
- Misc/Special Operator

If more than one operator is involved in an expression, c language has a predefined rule of priority for the operators. This rule of priority of operators is called operator precedence. The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operator direction to be evaluated; it may be left to right or right to left.

The precedence of arithmetic operators (*, %, /, +, -) is higher than the relational operators (==, != , >, <, >= ,<= ) and precedence of relational operators is higher than the logical operators ( && , || , ! ).

Let's understand the precedence by the example given below:

snippet

int value=10+20*10;

The value variable will contain **210** because * (multiplicative operator) is evaluated before + (additive operator).

Associativity of operators

Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left.

Example:1 == 2! = 3

In the above example, the operators "== " and "! =" have same precedence. The associativity of both == and != is left to right i.e. the expression on the left is executed first and moves towards the right.

The above expression is equivalent to

snippet

((1 == 2)! = 3

1 == 2 executes first and results 0 (false)

Later 0! = 3 executes and results 1 (true)

Output

1

Precedence and Associativity

The precedence and associativity of C operators is given below:

Category | Operator | Associativity |
---|---|---|

Postfix | () [] -> . ++ - - | Left to right |

Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |

Multiplicative | * / % | Left to right |

Additive | + - | Left to right |

Shift | << >> | Left to right |

Relational | < <= > >= | Left to right |

Equality | == != | Left to right |

Bitwise AND | & | Left to right |

Bitwise XOR | ^ | Left to right |

Bitwise OR | | | Left to right |

Logical AND | && | Left to right |

Logical OR | || | Left to right |

Conditional | ?: | Right to left |

Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |

Comma | , | Left to right |

Related Tutorial