C++ Operators Complete Guide
Precedence Rules

C++ Operators: Complete Guide with Examples

Master all C++ operators: arithmetic, relational, logical, bitwise, assignment, and special operators. Learn operator precedence, usage examples, and best practices.

Arithmetic

Math Operations

Relational

Comparison

Logical

Boolean Logic

Bitwise

Bit Operations

C++ Tutorial · Operators

Operators express calculations and decisions. This lesson covers every major operator family, evaluation order, and shortcuts that make C++ concise—but easy to misuse.

What you will learn

  • Apply arithmetic and assignment operators correctly
  • Combine relational and logical operators in conditions
  • Use bitwise operators for flags and masks
  • Understand prefix vs postfix increment
  • Follow operator precedence without surprises

Why this topic matters

Operator precedence bugs and short-circuit logic trip up beginners and appear in MCQ tests. Mastery here simplifies conditionals and loops.

Key terms & indexing

C++ operators operator precedence C++ bitwise operators C++ increment decrement C++

Introduction to C++ Operators

Operators are special symbols that perform operations on variables and values. C++ provides a rich set of operators that can be classified into several categories based on their functionality.

Operator Characteristics
  • Arity: Number of operands (unary, binary, ternary)
  • Precedence: Order of evaluation
  • Associativity: Direction of evaluation (left-to-right or right-to-left)
  • Overloadable: Can be redefined for user-defined types
Key Concepts
  • Operand: Value/variable on which operator acts
  • Expression: Combination of operators and operands
  • Lvalue vs Rvalue: Location vs value distinction
  • Side Effects: Changes to operands during evaluation

Basic Operator Example

Operators work with operands to form expressions: result = operand1 operator operand2

Quick Examples

1. Addition
int a = 10, b = 3;
int sum = a + b;  // 13
2. Modulus
int a = 10, b = 3;
int rem = a % b;  // 1
3. Equal check
int a = 10, b = 3;
bool eq = (a == b);  // false
4. Greater than
int a = 10, b = 3;
bool gt = (a > b);  // true
5. Logical AND
bool x = true, y = false;
bool r = x && y;  // false
6. Logical NOT
bool x = true;
bool r = !x;  // false

Complete C++ Operators Reference

The following table provides a comprehensive reference of all C++ operators with examples and descriptions:

Category Operator Name Description & Example
Arithmetic Operators
Arithmetic + Addition Adds two operands: a + b
Arithmetic - Subtraction Subtracts second operand: a - b
Arithmetic * Multiplication Multiplies two operands: a * b
Arithmetic / Division Divides numerator by denominator: a / b
Arithmetic % Modulus Remainder after division: a % b
Arithmetic ++ Increment Increases value by 1: a++ (post), ++a (pre)
Arithmetic -- Decrement Decreases value by 1: a-- (post), --a (pre)
Relational/Comparison Operators
Relational == Equal to Checks equality: a == b returns true if equal
Relational != Not equal to Checks inequality: a != b returns true if not equal
Relational > Greater than a > b returns true if a is greater
Relational < Less than a < b returns true if a is less
Relational >= Greater than or equal a >= b returns true if a is greater or equal
Relational <= Less than or equal a <= b returns true if a is less or equal
Logical Operators
Logical && Logical AND a && b returns true if both are true
Logical || Logical OR a || b returns true if either is true
Logical ! Logical NOT !a returns true if a is false
Bitwise Operators
Bitwise & Bitwise AND Sets each bit to 1 if both bits are 1: a & b
Bitwise | Bitwise OR Sets each bit to 1 if either bit is 1: a | b
Bitwise ^ Bitwise XOR Sets each bit to 1 if only one bit is 1: a ^ b
Bitwise ~ Bitwise NOT Inverts all bits: ~a
Bitwise << Left shift Shifts bits left, fills with 0: a << n
Bitwise >> Right shift Shifts bits right: a >> n
Assignment Operators
Assignment = Simple assignment Assigns right operand to left: a = b
Assignment += Add AND assign a += b is same as a = a + b
Assignment -= Subtract AND assign a -= b is same as a = a - b
Assignment *= Multiply AND assign a *= b is same as a = a * b
Assignment /= Divide AND assign a /= b is same as a = a / b
Assignment %= Modulus AND assign a %= b is same as a = a % b
Assignment &= Bitwise AND assign a &= b is same as a = a & b
Assignment |= Bitwise OR assign a |= b is same as a = a | b
Assignment ^= Bitwise XOR assign a ^= b is same as a = a ^ b
Assignment <<= Left shift AND assign a <<= n is same as a = a << n
Assignment >>= Right shift AND assign a >>= n is same as a = a >> n
Special Operators
Special ?: Ternary/Conditional condition ? expr1 : expr2 - If condition true, expr1 else expr2
Special , Comma expr1, expr2 - Evaluates both, returns expr2
Special sizeof Size of sizeof(type) - Returns size in bytes
Special typeid Type identification typeid(expr) - Returns type information
Special static_cast Static cast static_cast<type>(expr) - Compile-time type conversion
Special dynamic_cast Dynamic cast dynamic_cast<type>(expr) - Runtime type conversion (polymorphic)
Special const_cast Const cast const_cast<type>(expr) - Adds/removes const qualifier
Special reinterpret_cast Reinterpret cast reinterpret_cast<type>(expr) - Reinterprets bit pattern
Special . and -> Member access obj.member (direct), ptr->member (via pointer)
Special :: Scope resolution Class::member or namespace::member
Special new Dynamic memory allocation new type - Allocates memory on heap
Special delete Dynamic memory deallocation delete ptr - Frees heap memory
Special () Function call function(arg1, arg2) - Calls a function
Special [] Array subscript array[index] - Accesses array element

Operator Examples with Code

Arithmetic Operators

1. Addition
int a = 15, b = 4;
cout << a + b;  // 19
2. Integer division
int a = 15, b = 4;
cout << a / b;  // 3
3. Modulus
int a = 15, b = 4;
cout << a % b;  // 3
4. Float division
double x = 15.0, y = 4.0;
cout << x / y;  // 3.75
5. Post-increment
int c = 5;
cout << c++;  // prints 5, c=6
6. Pre-decrement
int c = 5;
cout << --c;  // prints 4

Relational and Logical Operators

1. Age check
int age = 25;
bool ok = (age >= 18);  // true
2. Not equal
int age = 25;
bool diff = (age != 30);  // true
3. AND (can drive)
int age = 25;
bool lic = true;
bool drive = (age >= 18) && lic;
4. OR (eligible)
int age = 25;
bool elig = (age > 21) || (salary > 40000);
5. NOT operator
int age = 25;
bool bad = !(age > 0);  // false
6. Short-circuit
int x = 5, y = 0;
bool safe = (y != 0) && (x / y > 2);

Bitwise Operators

1. Bitwise AND
unsigned char a = 53, b = 15;
int r = a & b;  // 5
2. Bitwise OR
unsigned char a = 53, b = 15;
int r = a | b;  // 63
3. Bitwise XOR
unsigned char a = 53, b = 15;
int r = a ^ b;  // 58
4. Left shift
unsigned char a = 53;
int r = a << 2;  // 212
5. Set flag
int flags = 0;
const int FLAG_A = 1 << 0;
flags |= FLAG_A;
6. Toggle flag
int flags = 1;
const int FLAG_B = 1 << 1;
flags ^= FLAG_B;

Operator Precedence and Associativity

Operator precedence determines the order of evaluation in expressions. When operators have the same precedence, associativity determines the direction of evaluation.

Important Rule

Use parentheses () to explicitly specify evaluation order when in doubt. This improves readability and prevents bugs.

Precedence Category Operators Associativity
1 (Highest) Scope resolution :: Left to right
2 Postfix () [] -> . ++ -- Left to right
3 Unary ++ -- + - ! ~ (type) * & sizeof Right to left
4 Member access .* ->* Left to right
5 Multiplicative * / % Left to right
6 Additive + - Left to right
7 Bitwise shift << >> Left to right
8 Relational < <= > >= Left to right
9 Equality == != Left to right
10 Bitwise AND & Left to right
11 Bitwise XOR ^ Left to right
12 Bitwise OR | Left to right
13 Logical AND && Left to right
14 Logical OR || Left to right
15 Conditional ?: Right to left
16 Assignment = += -= *= /= %= &= ^= |= <<= >>= Right to left
17 (Lowest) Comma , Left to right

Precedence Examples

1. Multiply before add
int a = 5, b = 10, c = 15;
int r = a + b * c;  // 155
2. Multiply first
int a = 5, b = 10, c = 15;
int r = a * b + c;  // 65
3. Relational + logical
int a = 5, b = 10, c = 15;
bool r = a > b && b < c;  // false
4. Parentheses override
int a = 5, b = 10, c = 15;
int r = (a + b) * c;  // 225
5. Group comparison
int a = 5, b = 10, c = 15;
bool r = (a > b) && (b < c);
6. Nested grouping
int a = 5, b = 10, c = 15;
int r = a * (b + c);  // 125
Undefined Behavior Warning: Avoid modifying the same variable multiple times in the same expression (e.g., x++ + ++x). The result is undefined and varies between compilers.

Special Operators in Detail

Ternary Operator

condition ? expr1 : expr2 - Compact if-else replacement.

int max = (a > b) ? a : b;
string result = (score >= 50) 
                ? "Pass" : "Fail";
sizeof Operator

Returns size in bytes of type or variable.

sizeof(int);      // 4 (usually)
sizeof(double);   // 8 (usually)
int arr[10];
sizeof(arr);      // 40 (if int is 4 bytes)
Type Cast Operators

C++ offers four casting operators for type conversion.

// Static cast (compile-time)
double d = 3.14;
int i = static_cast(d);

// Dynamic cast (runtime, polymorphic)
Base* b = new Derived();
Derived* d = dynamic_cast(b);
new and delete

Dynamic memory allocation and deallocation.

// Single object
int* ptr = new int(42);
delete ptr;

// Array
int* arr = new int[10];
delete[] arr;

Special Operator Examples

1. Ternary operator
int age = 20;
string st = (age >= 18) ? "Adult" : "Minor";
2. sizeof type
cout << sizeof(int);    // often 4
cout << sizeof(double);  // often 8
3. sizeof array
int arr[10];
cout << sizeof(arr);  // 40 if int=4
4. Scope resolution
int value = 100;
{
    int value = 200;
    cout << ::value;  // 100
}
5. Dot member access
struct Point { int x, y; };
Point p = {10, 20};
cout << p.x;
6. Arrow member access
struct Point { int x, y; };
Point p = {10, 20};
Point* ptr = &p;
cout << ptr->y;

Best Practices and Common Pitfalls

Do's
  • Use parentheses for complex expressions
  • Use compound assignment operators for brevity
  • Prefer prefix increment/decrement (++i) when value not needed
  • Use const with pointers to prevent modification
  • Check for division by zero before division/modulus
  • Use bitwise operators only for bit manipulation
  • Initialize variables before using them
Don'ts
  • Don't use assignment (=) instead of equality (==)
  • Don't modify same variable multiple times in one expression
  • Don't use bitwise operators as logical operators
  • Don't forget operator precedence (use parentheses)
  • Don't use C-style casts (use C++ casts instead)
  • Don't use sizeof on pointer types for array size
  • Don't ignore compiler warnings about type conversions
Common Operator Mistakes:
  1. if (x = 5) instead of if (x == 5) (assignment vs comparison)
  2. a < b < c instead of (a < b) && (b < c)
  3. Integer division when expecting floating-point: 5/2 = 2 not 2.5
  4. Using ! (logical NOT) instead of ~ (bitwise NOT)
  5. Forgetting that && and || use short-circuit evaluation

Good Practice Examples

1. Use parentheses
int r = (2 + 3) * 4;  // 20, not 11
2. Compound assignment
int total = 0;
total += 5;
total *= 2;  // total = 10
3. Check before divide
int num = 10, den = 0;
if (den != 0)
    cout << num / den;
4. == not =
int x = 5, y = 10;
if (x == y)  // compare
    cout << "Equal";
5. Chained comparison
int x = 3;
if (x > 0 && x < 5)
    cout << "In range";
6. static_cast
double pi = 3.14159;
int n = static_cast<int>(pi);  // 3

Frequently asked questions

What is the difference between && and &?

&& is logical AND (short-circuit); & is bitwise AND on integer bits.

Does i++ return the old value?

Postfix i++ returns the old value then increments; prefix ++i increments then returns the new value.

Which operator has highest precedence?

Scope, postfix increment, and unary operators rank high; consult a precedence table when in doubt.