Precedence and associativity have to do with operators. Let’s discuss them one by one.
Precedence is the order in operators with different precedence are evaluated.
In precedence, the operator with a higher precedence will be evaluated first. Then, the lower precedence operator is evaluated.
To understand this better, let’s look at the code snippet below.
#include <iostream>using namespace std;int main() {cout << 8 + (6 * 2) / 2 - 10 ;return 0;}
(6 * 2)
is evaluated while ()
takes precedence over all the operators. The expression now becomes 8 + 12 / 2 - 10
.8 + 6 - 10
.14 - 10
.4
.Now, let’s discuss associativity.
Associativity is the order in which operators with the same precedence are evaluated.
For example, if we have an addition and subtraction expression, the compiler will evaluate from left to right since they both have the same precedence.
This can be done in two ways:
Below is the list of operators in decreasing order of their precedence. The operators in the same row have the same precedence.
Category | Operators | Associativity |
Multiplicative | *, /, % | Left to right |
Additive | +, - | Left to right |
AND | & | Left to right |
OR | | | Left to right |
Shift | <<, >> | Left to right |
Equality | ==, |= | Left to right |
Conditional | ?, : | Right to left |
Assignment | +=, -=, *=, /=, >>=, <<=, &=, |=, ^=, == | Right to left |
To understand this better, take a look at the code snippet below.
#include <iostream>using namespace std;int main() {cout << 12*6/8*3*2/6 ;}
12 * 6
will be evaluated while *
and /
have the same precedence, which is evaluated from left to right. The expression will then become
72 / 8 * 3 * 2 / 6
.72 / 8
will be evaluated, and the expression becomes 9 * 3 * 2 / 6
.9
.This is how precedence and associativity work in operators in C++.