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.
- 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.
- 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.
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