So far we have gone through the following operators in C++:

Now let’s first understand what is meant by an expression. An expression is a sequence consisting of variables, constants and operators which specify a computation. That is, an expression can be evaluated to give a result. For example : num1 + 12 and (num1 – 45 ) / 4 + num2 are expressions consisting of variables num1 and num2 which may be of any data type.

In C++, the compiler follows a certain procedure to evaluate such expressions. A particular order of operations is followed. This order depends on the precedence of operators. High precedence operators are evaluated before any low precedence operators.

The following table lists various operators in the order of their precedence starting from highest to lowest.

Operator Category Operators Precedence
Unary !, ++, –, +, – Highest
Arithmetic *, /, %
+, –
Relational <, >, <=, >=
==, !=
Logical &&
||
Conditional ?:
Assignment =, +=, -=, *=, /=, %= Lowest

Some important points about precedence:

  1. Operators on the same row have equal precedence. They are evaluated from left to right in an expression.
  2. You can force an expression to be evaluated first by using parenthesis. For example: In (a-b)*c,  a-b will be evaluated first and then multiplied with c.
  3. However, if we have a-b*c,  b*c will be evaluated first and then subtracted from a.
  4. It is also recommended to use parenthesis  for enhancing the readability of expressions.

The following program illustrates the concepts explained in this lesson.

In the above program, you can see how operator precedence is used by the compiler to evaluate various expressions. Refer to the precedence table above to evaluate the expressions yourself and verify your answers with the program output.
Here is a live preview of the program.

Precedence of operators in C++

We hope you’re clear with this lesson. Do let us know your queries. Drop you comments below.




Tags: ,

Leave A Response