C++ Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, associativity determines the order of evaluation.

Key Rules

  • Operators with higher precedence are executed first.
  • Associativity can be left-to-right or right-to-left depending on the operator.
  • Parentheses ( ) can be used to override default precedence and ensure the desired order of evaluation.

Common Operator Precedence in C++

PrecedenceOperator(s)DescriptionAssociativity
1() [] . ->Parentheses, Array subscript, Member accessLeft-to-right
2! ~ ++ — + – * & sizeofUnary operators, logical NOT, bitwise NOT, increment/decrement, unary plus/minus, dereference, address-ofRight-to-left
3* / %Multiplication, Division, ModulusLeft-to-right
4+ –Addition, SubtractionLeft-to-right
5<< >>Bitwise shift left and rightLeft-to-right
6< <= > >=Relational operatorsLeft-to-right
7== !=Equality and inequalityLeft-to-right
8&Bitwise ANDLeft-to-right
9^Bitwise XORLeft-to-right
10|Bitwise ORLeft-to-right
11&&Logical ANDLeft-to-right
12||Logical ORLeft-to-right
13= += -= *= /= %= <<= >>= &= ^= |=Assignment operatorsRight-to-left
14,Comma operatorLeft-to-right

Example Program

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 3, c = 2;
    int result;

    // Without parentheses
    result = a + b * c; // Multiplication (*) has higher precedence than addition (+)
    cout << "a + b * c = " << result << endl;

    // Using parentheses
    result = (a + b) * c; // Parentheses override precedence
    cout << "(a + b) * c = " << result << endl;

    return 0;
}

Output

a + b * c = 11
(a + b) * c = 16

Important Notes

  • Always use parentheses to make complex expressions clear and avoid mistakes.
  • Operator precedence rules are especially important when combining multiple types of operators.
  • Consult C++ documentation for full precedence tables if needed.

Next Topic

After mastering operators and precedence, you can move on to C++ Control Structures like if-else statements and loops.