What is precedence and associativity in C++?

Precedence and associativity have to do with operators. Let’s discuss them one by one.

Precedence

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;
}

Explanation:

  • In line 5, we print the result of an expression. The expression is evaluated as follows:
    • First, (6 * 2) is evaluated while () takes precedence over all the operators. The expression now becomes 8 + 12 / 2 - 10.
    • Now, the division operator is evaluated, and the expression becomes 8 + 6 - 10.
    • Then, the addition operator takes precedence and is evaluated. The expression becomes 14 - 10.
    • We are left with subtraction expression that, when evaluated, returns the final result of 4.

Now, let’s discuss associativity.

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:

  • Left to right
  • Right to left

Below is the list of operators in decreasing order of their precedence. The operators in the same row have the same precedence.

List of operators with decreasing order of 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 ;
}

Explanation:

  • In line 5, we print the result of the expression. The expression is evaluated as shown:
    • First, 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.
    • Then, 72 / 8 will be evaluated, and the expression becomes 9 * 3 * 2 / 6.
    • All the operators will then operate from left to right until we get the final result of 9.

This is how precedence and associativity work in operators in C++.