C++ Expression Evaluation

In the C++ programming language, an expression is evaluated based on the operator precedence and associativity. When there are multiple operators in an expression, they are evaluated according to their precedence and associativity. The operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.

To understand expression evaluation in c, let us consider the following simple example expression.

Example code
10 + 4 * 3 / 2

In the above expression, there are three operators +, * and /. Among these three operators, both multiplication and division have the same higher precedence and addition has lower precedence. So, according to the operator precedence both multiplication and division are evaluated first and then the addition is evaluated. As multiplication and division have the same precedence they are evaluated based on the associativity. Here, the associativity of multiplication and division is left to right. So, multiplication is performed first, then division and finally addition. So, the above expression is evaluated in the order of * / and +. It is evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

Operator Precedance

In any programming language, every operator has provided a preference that is used at the time of expression evaluation. In C++, the following list provides the operators' preference from higher to lower.

  1. Pre-increment (or) pre- decrement
  2. Peranthasis , shifting operators , sizeof
  3. Astrick (*) , multiplication and division
  4. Addition , substraction
  5. Relational operators
  6. Assignment operators
  7. Post increment/post decrement