3.6 Operator Precedence in C

Operator Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others.
For example, the multiplication operator has a higher precedence than the addition operator.
i.e. x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence. There are two distinct priority levels of arithmetic operators in C.

  • Higher Priority * / 
  • Lower Priority + - 
The expression x=a-b/3+c*2-1 where a=9, b=12 and c=3 will be evaluated as:

Step 1: x=9-12/3+3*2-1
Higher priority operators left to right division first

Step 2: x=9-4+3*2-1
Higher priority operators left to right multiply

Step 3: x=9-4+6-1
Lower priority operators left to right subtraction

Step 4: x=5+6-1
Lower priority operators left to right addition

Step 5: x=11-1
Lower priority operators left to right subtraction

Step 6: x=10
Final Result

Rules for Evaluation of Expression
  • First, parenthesized sub expression from left to right are evaluated.
  • If parentheses are nested, the evaluation begins with innermost sub expression.
  • The precedence rule is applied in determining the order of operands in evaluating sub expressions.
  • Arithmetic expressions are evaluated from left to right using the rules of precedence.
  • When parentheses are used, the expressions within the parentheses assume highest priority.

No comments:

Post a Comment