C++ Operator Precedence and Associativity

Operator precedence determines the order in which operators are evaluated in an expression. Associativity decides the order when operators have the same precedence. Understanding this helps avoid logical errors in complex expressions.

1. Operator Precedence Table

PrecedenceOperator(s)DescriptionAssociativityExample
1()Parentheses (grouping)Left-to-rightx = (a + b) * c;
2++ -- (prefix), +, -, !, ~Unary operatorsRight-to-left++a; -b; !flag;
3* / %Multiplication, Division, ModulusLeft-to-righta * b / c % d;
4+ -Addition, SubtractionLeft-to-righta + b - c;
5<< >>Bitwise shiftLeft-to-righta << 2; b >> 1;
6< <= > >=Relational operatorsLeft-to-righta < b; c >= d;
7== !=Equality operatorsLeft-to-righta == b; a != b;
8&Bitwise ANDLeft-to-righta & b;
9^Bitwise XORLeft-to-righta ^ b;
10|Bitwise ORLeft-to-righta | b;
11&&Logical ANDLeft-to-righta && b;
12||Logical ORLeft-to-righta || b;
13?:Ternary conditionalRight-to-leftmax = (a > b) ? a : b;
14=+=-=*=/=%=&=|=^=<<=>>=Assignment operatorsRight-to-lefta = b; c += d;
15,Comma operator (expression sequencing)Left-to-rightx = (a++, b++);

2. Examples of Operator Precedence

C++
Demonstrating operator precedence
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 10, c = 15;
    int result;

    // Multiplication has higher precedence than addition
    result = a + b * c;
    cout << "a + b * c = " << result << endl; // 5 + (10*15) = 155

    // Parentheses override precedence
    result = (a + b) * c;
    cout << "(a + b) * c = " << result << endl; // (5+10)*15 = 225

    // Ternary operator example
    int max = (a > b) ? a : b;
    cout << "Maximum = " << max << endl;

    // Comma operator example
    int x;
    x = (a++, b++, c++);
    cout << "Value of x using comma operator: " << x << endl;

    return 0;
}

Conclusion

Understanding operator precedence and associativity in C++ is crucial for writing correct expressions. Using parentheses can clarify intent and prevent unexpected results in complex statements.