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++
| Precedence | Operator(s) | Description | Associativity |
|---|---|---|---|
| 1 | () [] . -> | Parentheses, Array subscript, Member access | Left-to-right |
| 2 | ! ~ ++ — + – * & sizeof | Unary operators, logical NOT, bitwise NOT, increment/decrement, unary plus/minus, dereference, address-of | Right-to-left |
| 3 | * / % | Multiplication, Division, Modulus | Left-to-right |
| 4 | + – | Addition, Subtraction | Left-to-right |
| 5 | << >> | Bitwise shift left and right | Left-to-right |
| 6 | < <= > >= | Relational operators | Left-to-right |
| 7 | == != | Equality and inequality | Left-to-right |
| 8 | & | Bitwise AND | Left-to-right |
| 9 | ^ | Bitwise XOR | Left-to-right |
| 10 | | | Bitwise OR | Left-to-right |
| 11 | && | Logical AND | Left-to-right |
| 12 | || | Logical OR | Left-to-right |
| 13 | = += -= *= /= %= <<= >>= &= ^= |= | Assignment operators | Right-to-left |
| 14 | , | Comma operator | Left-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.