Labs ICT
Pro Login

Operator Precedence

Operator precedence tells C++ which operations to perform first when you have a complicated expression. Just like in math, multiplication happens before addition. If you have 5 + 3 * 2, the result is 11, not 16, because multiplication has higher precedence.

Precedence Rules

Here are the most common precedence rules from highest to lowest:

  • () — parentheses, highest precedence
  • * / % — multiplication, division, modulo
  • + - — addition, subtraction
  • << >> — stream operators (cout, cin)
  • < > <= >= — comparison operators
  • == != — equality operators
  • = — assignment, lowest precedence

When in doubt, use parentheses. They make your intention clear and prevent bugs. There is no shame in writing (a + b) * c instead of relying on precedence. Code is read by humans first, computers second.

#include <iostream>
using namespace std;

int main() {
  int result1 = 5 + 3 * 2;
  int result2 = (5 + 3) * 2;
  int result3 = 20 - 10 / 2 + 3;
  int result4 = (20 - 10) / (2 + 3);

  cout << "5 + 3 * 2 = " << result1 << endl;
  cout << "(5 + 3) * 2 = " << result2 << endl;
  cout << "20 - 10 / 2 + 3 = " << result3 << endl;
  cout << "(20 - 10) / (2 + 3) = " << result4;
  return 0;
}

Look at the results. result1 gives 11 because multiplication happens first. result2 gives 16 because parentheses force addition first. The same expression without parentheses can give very different results depending on precedence. That is why parentheses are your friend.