coderz.py

Keep Coding Keep Cheering!

Precedence of Operators in C

Matrix multiplication

While executing an arithmetic operation the precedence of the operators in C as well as other programming language matters a lot because precedence determines the grouping of terms in an expression and decides how an expression is evaluated. For instance, the expression might be having various arithmetic operators like ‘+’, ‘-‘, or ‘*’; then how to know which part of the expression gets executed first.

Priority of Operators:

Let us take a look at the precedence of commonly used operators :

here the priority goes from high(* / %) to low(=):

OperatorDescription
* / %multiplication, division, modular division
+ –addition, subtraction
=assignment
Associativity of Operators:

When an expression contains two operators of equal priority the tie between them is settled using the associativity of the operators. Associativity can be of two types – left to right or right to left:

  • Left to right associativity means that the left operand must be unambiguous i.e., it must not be involved in the evaluation of any other sub-expression.
  • Likewise, in case of right to left associativity, the right operand must be ambiguous.
CategoryOperatorAssociativity
Postfix() [] -> . ++ – –Left to right
Unary+ – ! ~ ++ – – (type)* & sizeofRight 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
Associativity with high to low priority

Consider the expression-

a = 3 / 1 * 5 ;
output: 15

Here there is a tie between operators of same priority, that is between / and *. This tie is settled using the associativity of / and * since both / and * have L to R associativity and only / has unambiguous left operand ,therefore / is performed earlier.

note: also read about  Variables & Constants in C & Operators in C.

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement