Monday, July 8, 2013

Operator Precedence in C

In C, we perform many operations. In such operations, generally we come across a problem or ambiguity. Ambiguity means possibility of getting different answers for the same expression. We can clearly understand what is ambiguity by observing the following example,
x=3+4*5;
So, what would be the answer to the above equation. Let us solve the same equation in two different ways.


1. By Addition first and then multiplication:

Then the solution turns as
x=7*5
and hence the answer would be 35.

2.By Multiplying first and then adding: 

Then the solution is
x=3+20;
and hence the answer is 23.

So in the above mentioned two ways, what is the correct approach in solving the expression. So, C language has observed a operator precedence to solve this problem. The following table gives the precedence of the operators.

Operators
Relative Precedence
++, --
1
*, /, %
2
+, -
3

Importance of Parenthesis:

Parenthesis has more importance than all the operators. Suppose in an expression, there exists a parenthesis, then the content inside the parenthesis need to be executed first and then the remaining expression is evaluated.

For example, 
x=(3+4)*5;
In the above example, even if * has more precedence than +, the expression inside the parenthesis i.e., addition is performed, hence the result is 35.