C++ Operators and Precedence: The Complete Master Reference Guide

An Operator is a special symbol that tells the compiler to perform specific mathematical, relational, or logical manipulations on operands. C++ features a rich variety of operators with strict precedence and associativity rules.

Key Operator Categories

  • Arithmetic Operators: +, -, *, /, % (modulus).
  • Relational / Comparison Operators: ==, !=, >, <, >=, <=, and C++20 Three-way comparison <=> (spaceship operator).
  • Logical Operators: && (AND), || (OR), ! (NOT).
  • Bitwise Operators: &, |, ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
  • Assignment Operators: =, +=, -=, *=, /=, %=, &=, |=.
  • Ternary Conditional Operator: condition ? expr1 : expr2.

Operator Precedence Summary Table (Highest to Lowest)

Precedence Level Operators Associativity
1 (Highest) Scope resolution :: Left to Right
2 Member access ., ->, Subscript [], Function call (), Postfix ++, -- Left to Right
3 Prefix ++, --, Unary +, -, Logical NOT !, Bitwise NOT ~, Dereference *, Address-of &, sizeof Right to Left
4 Multiplication *, Division /, Modulo % Left to Right
5 Addition +, Subtraction - Left to Right
6 Bitwise Shift <<, >> Left to Right
7 Relational <, <=, >, >= Left to Right
8 Equality ==, != Left to Right
9 Logical AND && Left to Right
10 Logical OR || Left to Right
11 Ternary Conditional ? : Right to Left
12 (Lowest) Assignment =, +=, -=, Comma , Right to Left

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is Short-Circuit Evaluation in C++ logical operators?

In logical AND (&&), if the left condition evaluates to false, the right condition is never executed because the whole expression cannot be true. In logical OR (||), if the left condition is true, the right condition is skipped. This is critical for preventing null pointer dereferences (e.g., if (ptr != nullptr && ptr->val > 0)).

Q2. What is the difference between prefix (++x) and postfix (x++) increment?

Prefix (++x) increments the value immediately and returns the newly incremented value. Postfix (x++) makes a temporary copy of the current value, increments the original variable, and returns the old copy. In modern C++ loops and iterators, prefix (++it) is preferred for performance.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Operator Overloading

Teach your custom classes how to use +, -, << and ==.

C++ If-Else

Using relational and logical operators in decision making.

C++ Switch

Multi-way branching based on integral operators.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!