Saturday 30 December 2017

Operator Precedence and Associativity in C Language

Interesting facts about Operator Precedence and Associativity in C Language

Operator precedence decides which operator’s operation should be performed first in an expression with more than one operators with different precedence.

For example 8+ 2 * 10 is calculated as 8 + (2 * 10) and not as (8 + 2) * 10.

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

For example ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub expressions in absence of brackets.
  • Associativity is used only when there are two or more operators of same precedence. Associativity doesn’t define the order in which operands of a single operator are evaluated. 
       For example associativity of the * operator is high so 2*3 performed first that 6+1 that is 7 assigned to a.          int a = 1+2*3;
  • All operators with same precedence have same associativity. This is necessary, otherwise there won’t be any way for compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. 
      For example + and – have same associativity.
  • Precedence and associativity of postfix ++ and prefix ++ are different
  • Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. 
Click here for more on Pre/post increments.
  • Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.
#include
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
}


 Output:
1

No comments:

Post a Comment

Thank you for your Time. Keep Learning

Geeks4Coding

Contributors

Popular Posts