“Precedent perpetuates the principle” Benjamin Disraeli
In this section we’re assuming you’re familiar with arithmetic operators.
Let’s start with a simple expression:
`int iVar = 10 – 2 * 4 /2`;
What do you think is the final value assigned to the iVar variable?
The final value assigned to the iVar is 6. But how we get this value?
This is where precedence comes in.
Based on precedence rules, arithmetic operators have different priority.
For example the multiplication * operator has higher priority than addition + operator and so if we had an expression like 10+5*2 the result will be 20. This means in the expression before, first the two values 5 and 2 will be multiplied together and the result will be added to the value 10.
In the list below you can see operators in order of decreasing precedence:
| Operators | Associativity |
|---|---|
| () | Left to Right |
| * / | Left to Right |
| + – | Left to Right |
| = | Right to Left |
As the table above shows, the highest precedence belongs to parentheses and after that we have multiplication& division and next is addition& subtraction and at the end we have assign operator with lowest precedence.
For example if we had an expression like this:
int iVar = (10 + 20) * 10;
First because the parentheses have higher priority than multiplication, the result in the parentheses should be declared first (which will be 30) and then the result is multiplied by 10 (so the final result is 300) and at the end this result is assigned to the variable iVar.
Associativity:
Associativity declares the order of operand execution.
For example the associativity in arithmetic operators is from Left to Right. This means if we have an expression like (4/2)*4, the left operand executes first and then the right operand. So the result is:
2*4 = 8.
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10 ;
int b = 20;
int c = 30 ;
int d = 40;
int result = (a+b) * d; // (10+20) * 40
cout<<"The result is: "<< result<<endl;
result = ((a+b) /2) * c; // ((10+20)/2) * 30
cout<<"The result is: "<< result<<endl;
result = c+d/10 * d; // 30+((40/10) * 40)
cout<<"The result is: "<< result<<endl;
return 0;
}
Output:
The result is: 1200
The result is: 450
The result is: 190