Operator Precedence and Associativity in C++

When an expression contains multiple operators, the order in which different operators are evaluated is known as operator precedence. Suppose if we want to evaluate an expression 10*3+2 then we should know that whether multiplication (*) will be evaluated first or addition (+). Using normal mathematical precedence rules, we know that multiplication has higher precedence than addition. So, multiplication will take place first and then addition is held. So, expression will be evaluated as (10*3) +2 producing 32. Operator precedence is also known as hierarchy of operators.

If two operators have same precedence then the order in which operators are evaluated is known as Operator Associativity. It can be “left to right” or “right to left”.

In C++, Each operator is assigned a level of precedence. If an expression contains different types of operators, the operators with high precedence are evaluated before the operators with lower precedence. The order of precedence and their associativity in C++ language is as follows:

To solve general expressions, we can conclude that:

1: Any expression given in parenthesis is evaluated first.

2: Multiplication (*) and division (/) operators have equal precedence.

3: Addition (+) and subtraction (-) operators have equal precedence.

4: In case of parenthesis within parenthesis, the expressing of the inner parenthesis will be evaluated first.

Good Reference Article: Even or Odd Program in C++

Let’s solve two expressions by using above given results.

Example 1:

  • First of all, the parenthesis inside parenthesis are evaluated as 20/4=5
  • Then, the expression attained inside the parenthesis is evaluated as 3*5=15.
  • Although plus (+) and minus (-) have same priority but associativity is “left to right” and plus (+) is    present on left side. So, it will be evaluated first like 7+15=22.
  • At the end, 13 would be subtracted from 22 and gives the final result 9.

Example 2:

In this expression:
  • 7+3 comes inside the parenthesis and evaluated first as 10.
  • Now, we have 3 operators in our expression i.e. 1 minus and 2 asterisks. We know that multiplication have higher precedence as compared to subtraction. So, asterisks will be evaluated before minus. But we also have two asterisks and which one will be evaluated first? One who comes at the left side. So, 6*10 will be evaluated as 60.
  • After that, 60 is multiplied with 2 giving 120.
  • Now, 3 is subtracted from 120 and 117 is attained.

About Author:

Kamal Choudhary is a tech geek who writes C++ programming tutorials. He is a student of computer science in University of Gujrat, pakistan. He loves to write about computer programming. Follow him on twitter @ikamalchoudhary


Post a Comment