Precedence of Operators

Precedence and associativity are the two important properties of operators. Precedence is the order in which a program performs / evaluates the operation in a formula. All operators have a precedence value. An operator with higher precedence is evaluated before an operator with a lower precedence value.

When making complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression:

a = 5 + 7 % 2

we may doubt if it really means:

a = 5 + (7 % 2) with result 6, or

a = (5 + 7) % 2 with result 0

The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference we may already know from mathematics) but for all the operators which can appear in C++.

From greatest to lowest priority, the priority order is as follows

Left to right associativity means evaluation is performed from left to right. the compiler starts from the left side. Similarly, right to left associativity means evaluation is performed from right to left.

  • Multiplication has a higher precedence than addition.

  • Assignment operators are evaluated in right to left order.

  • the order of precedence can be changes by using parentheses in the expression.

  • the variables in the expression within parentheses are evaluated before any of other mathematical operator.