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
| Precedence | Operator(s) | Description | Associativity | Example | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | () | Parentheses (grouping) | Left-to-right | x = (a + b) * c; | ||||||||||
| 2 | ++ -- (prefix), +, -, !, ~ | Unary operators | Right-to-left | ++a; -b; !flag; | ||||||||||
| 3 | * / % | Multiplication, Division, Modulus | Left-to-right | a * b / c % d; | ||||||||||
| 4 | + - | Addition, Subtraction | Left-to-right | a + b - c; | ||||||||||
| 5 | << >> | Bitwise shift | Left-to-right | a << 2; b >> 1; | ||||||||||
| 6 | < <= > >= | Relational operators | Left-to-right | a < b; c >= d; | ||||||||||
| 7 | == != | Equality operators | Left-to-right | a == b; a != b; | ||||||||||
| 8 | & | Bitwise AND | Left-to-right | a & b; | ||||||||||
| 9 | ^ | Bitwise XOR | Left-to-right | a ^ b; | ||||||||||
| 10 | | | Bitwise OR | Left-to-right | a | b; | ||||||||||
| 11 | && | Logical AND | Left-to-right | a && b; | ||||||||||
| 12 | || | Logical OR | Left-to-right | a || b; | ||||||||||
| 13 | ?: | Ternary conditional | Right-to-left | max = (a > b) ? a : b; | ||||||||||
| 14 | = | += | -= | *= | /= | %= | &= | |= | ^= | <<= | >>= | Assignment operators | Right-to-left | a = b; c += d; |
| 15 | , | Comma operator (expression sequencing) | Left-to-right | x = (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.
Codecrown