Topic 14 of 91 2. C++ Fundamentals Interactive Tutorial

C++ Operators Reference: Categories, Syntax, and Practical Usage

16 mins read Last updated: 26 Sep 2026 23,400 views

Direct Answer & Core Concept

Operators are an important part of C++ programming. They allow you to perform calculations, compare values, assign data, check conditions, and manipulate individual bits.

For example, when you write a + b, the plus (+) symbol tells C++ to add the values of two variables. Similarly, operators such as ==, &&, and ++ perform comparison, logical, and increment operations.

But C++ has many different operators, and each one has a specific purpose.

In this tutorial, you will learn about C++ operators, their categories, syntax, symbols, and practical uses. You will also explore examples of arithmetic, relational, logical, assignment, bitwise, conditional, and other operators.

Whether you are learning C++ for the first time or looking for a quick reference, this guide will help you understand how operators work.

Detailed Explanation & Mechanics

What Are Operators in C++?

An operator in C++ is a symbol or keyword that performs a particular operation on one or more values or variables.

The values on which an operator works are called operands.

For example:

main.cpp
Run Online
int a = 10;
int b = 20;

int result = a + b;

In this example:

  • a and b are operands.

  • + is the addition operator.

  • = is the assignment operator.

  • result stores the calculated value.

Output:

Operators are used throughout C++ programs to perform calculations, make decisions, and manipulate data.

Categories of Operators in C++

C++ provides several categories of operators. Each category is designed for a different type of operation.

The main categories include:

  1. Arithmetic operators

  2. Relational operators

  3. Logical operators

  4. Assignment operators

  5. Increment and decrement operators

  6. Bitwise operators

  7. Conditional operator

  8. Comma operator

  9. Member access operators

  10. Pointer operators

  11. Memory management operators

  12. Type and size operators

Let's understand each category with its syntax and practical examples.

1. Arithmetic Operators in C++

Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, division, and finding remainders.

These operators are commonly used in calculators, billing applications, financial programs, and mathematical operations.

Arithmetic Operators Reference

OperatorNameDescriptionExample
+AdditionAdds two valuesa + b
-SubtractionSubtracts one value from anothera - b
*MultiplicationMultiplies two valuesa * b
/DivisionDivides one value by anothera / b
%ModulusReturns the remaindera % b

Example: Arithmetic Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 20;
    int b = 10;

    cout << "Addition: " << a + b << endl;
    cout << "Subtraction: " << a - b << endl;
    cout << "Multiplication: " << a * b << endl;
    cout << "Division: " << a / b << endl;
    cout << "Modulus: " << a % 3 << endl;

    return 0;
}

Output:

main.cpp
Run Online
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Modulus: 2

Practical Uses of Arithmetic Operators

  • Calculate product prices and totals.

  • Find the average of students' marks.

  • Calculate discounts and percentages.

  • Perform mathematical calculations.

  • Determine whether a number is even or odd using %.

For example, to check whether a number is even:

main.cpp
Run Online
int number = 20;

if (number % 2 == 0) {
    cout << "Even Number";
}

2. Relational Operators in C++

Relational operators are used to compare two values.

They return a Boolean result: true or false.

These operators are useful when checking conditions in if, while, and for statements.

Relational Operators Reference

OperatorNameDescriptionExample
==Equal toChecks whether values are equala == b
!=Not equal toChecks whether values differa != b
>Greater thanChecks whether the left value is greatera > b
<Less thanChecks whether the left value is smallera < b
>=Greater than or equal toChecks whether the left value is greater or equala >= b
<=Less than or equal toChecks whether the left value is smaller or equala <= b

Example: Relational Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 20;
    int b = 10;

    cout << boolalpha;

    cout << "Equal: " << (a == b) << endl;
    cout << "Not Equal: " << (a != b) << endl;
    cout << "Greater: " << (a > b) << endl;
    cout << "Less: " << (a < b) << endl;
    cout << "Greater or Equal: " << (a >= b) << endl;
    cout << "Less or Equal: " << (a <= b) << endl;

    return 0;
}

Output:

main.cpp
Run Online
Equal: false
Not Equal: true
Greater: true
Less: false
Greater or Equal: true
Less or Equal: false

Practical Uses of Relational Operators

  • Compare students' marks.

  • Check a person's age.

  • Compare product prices.

  • Validate minimum and maximum limits.

  • Check whether a value matches a condition.

3. Logical Operators in C++

Logical operators are used to combine or reverse conditions.

They are especially useful when a program needs to check more than one condition at a time.

C++ provides three main logical operators.

Logical Operators Reference

OperatorNameDescriptionExample
&&Logical ANDTrue when both conditions are truea > 5 && b < 20
``Logical ORTrue when at least one condition is true`a > 5b < 20`
!Logical NOTReverses a Boolean value!(a > 5)

Example: Logical Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int age = 25;
    int salary = 30000;

    cout << boolalpha;

    cout << (age >= 18 && salary >= 20000) << endl;

    cout << (age < 18 || salary >= 20000) << endl;

    cout << !(age >= 18) << endl;

    return 0;
}

Output:

Explanation

  • AND (&&) checks whether both conditions are true.

  • OR (||) checks whether at least one condition is true.

  • NOT (!) reverses the result of a condition.

Practical Uses of Logical Operators

  • Check user login credentials.

  • Validate age and eligibility.

  • Check multiple conditions in a program.

  • Control access to restricted features.

  • Validate form inputs.

Important: C++ uses short-circuit evaluation for && and ||. For example, if the first condition in an AND expression is false, the second condition is not evaluated.

4. Assignment Operators in C++

Assignment operators are used to assign values to variables.

The most basic assignment operator is =.

C++ also provides compound assignment operators that perform an operation and assign the result back to the same variable.

Assignment Operators Reference

OperatorNameExampleEquivalent form
=Assignmenta = 10Assigns 10
+=Addition assignmenta += 5a = a + 5
-=Subtraction assignmenta -= 5a = a - 5
*=Multiplication assignmenta *= 2a = a * 2
/=Division assignmenta /= 2a = a / 2
%=Modulus assignmenta %= 3a = a % 3
&=Bitwise AND assignmenta &= 3a = a & 3
`=`Bitwise OR assignment`a= 3``a = a3`
^=Bitwise XOR assignmenta ^= 3a = a ^ 3
<<=Left shift assignmenta <<= 1a = a << 1
>>=Right shift assignmenta >>= 1a = a >> 1

Example: Assignment Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 10;

    number += 5;
    cout << "After += : " << number << endl;

    number -= 3;
    cout << "After -= : " << number << endl;

    number *= 2;
    cout << "After *= : " << number << endl;

    number /= 4;
    cout << "After /= : " << number << endl;

    return 0;
}

Output:

main.cpp
Run Online
After += : 15
After -= : 12
After *= : 24
After /= : 6

Practical Uses of Assignment Operators

  • Update account balances.

  • Increase product quantities.

  • Calculate running totals.

  • Update scores in games.

  • Modify counters in loops.

5. Increment and Decrement Operators in C++

Increment and decrement operators are used to increase or decrease the value of a variable by one.

They are frequently used in loops and counting operations.

Increment and Decrement Operators Reference

OperatorNameDescription
++aPrefix incrementIncreases the value before using it
a++Postfix incrementUses the original value before increasing it
--aPrefix decrementDecreases the value before using it
a--Postfix decrementUses the original value before decreasing it

Example: Increment and Decrement

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 10;

    cout << "Original: " << a << endl;

    cout << "Prefix Increment: " << ++a << endl;

    cout << "Postfix Increment: " << a++ << endl;

    cout << "After Increment: " << a << endl;

    cout << "Prefix Decrement: " << --a << endl;

    cout << "Postfix Decrement: " << a-- << endl;

    cout << "Final Value: " << a << endl;

    return 0;
}

Output:

main.cpp
Run Online
Original: 10
Prefix Increment: 11
Postfix Increment: 11
After Increment: 12
Prefix Decrement: 11
Postfix Decrement: 11
Final Value: 10

Practical Uses of Increment and Decrement

  • Count the number of iterations in a loop.

  • Increase or decrease a counter.

  • Move through array indexes.

  • Track the number of users or products.

  • Update game scores.

6. Bitwise Operators in C++

Bitwise operators perform operations on the individual bits of integer values.

They are commonly used in embedded programming, networking, system development, and low-level programming.

Bitwise Operators Reference

OperatorNameDescription
&Bitwise ANDSets a bit when both corresponding bits are 1
``Bitwise ORSets a bit when either corresponding bit is 1
^Bitwise XORSets a bit when corresponding bits differ
~Bitwise NOTInverts the bits
<<Left shiftShifts bits to the left
>>Right shiftShifts bits to the right

Example: Bitwise Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 5;
    int b = 3;

    cout << "AND: " << (a & b) << endl;
    cout << "OR: " << (a | b) << endl;
    cout << "XOR: " << (a ^ b) << endl;
    cout << "Left Shift: " << (a << 1) << endl;
    cout << "Right Shift: " << (a >> 1) << endl;

    return 0;
}

Output:

main.cpp
Run Online
AND: 1
OR: 7
XOR: 6
Left Shift: 10
Right Shift: 2

Binary Explanation

The binary representation of 5 is 0101, and the binary representation of 3 is 0011.

OperationBinary resultDecimal result
5 & 300011
`53`01117
5 ^ 301106
5 << 1101010
5 >> 100102

These examples use positive integers and a four-bit illustration. Actual C++ integer operations use the full width of the operand type.

7. Conditional Operator in C++

The conditional operator ?: is also called the ternary operator because it works with three operands.

It provides a short way to select one of two expressions based on a condition.

Syntax

main.cpp
Run Online
condition ? value_if_true : value_if_false;

Example: Conditional Operator

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 20;
    int b = 10;

    int largest = (a > b) ? a : b;

    cout << "Largest Number: " << largest;

    return 0;
}

Output:

Practical Uses

  • Find the largest or smallest of two numbers.

  • Choose between two values.

  • Display different messages based on a condition.

  • Perform simple conditional assignments.

8. Comma Operator in C++

The comma operator , evaluates multiple expressions from left to right and produces the value of the rightmost expression.

Syntax

main.cpp
Run Online
expression1, expression2, expression3;

Example: Comma Operator

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a, b, result;

    result = (a = 10, b = 20, a + b);

    cout << "Result: " << result;

    return 0;
}

Output:

The comma operator is useful when you specifically need multiple expressions to be evaluated in sequence. Do not confuse it with commas used to separate function arguments or variable declarations.

9. Member Access Operators in C++

Member access operators are used to access the data members and functions of objects.

C++ provides two commonly used member access operators.

Member Access Operators Reference

OperatorNamePurpose
.Dot operatorAccesses members through an object
->Arrow operatorAccesses members through a pointer

Example: Dot Operator

main.cpp
Run Online
#include <iostream>
using namespace std;

class Student {
public:
    int age = 20;
};

int main() {

    Student s;

    cout << "Age: " << s.age;

    return 0;
}

Output:

Example: Arrow Operator

main.cpp
Run Online
#include <iostream>
using namespace std;

class Student {
public:
    int age = 20;
};

int main() {

    Student s;

    Student* ptr = &s;

    cout << "Age: " << ptr->age;

    return 0;
}

Output:

The arrow operator accesses a member through a pointer. It is equivalent to dereferencing the pointer and then using the dot operator.

10. Pointer Operators in C++

Pointers are variables that store memory addresses.

C++ provides operators that allow you to work with pointers.

Pointer Operators Reference

OperatorNamePurpose
&Address-ofGets the address of a variable
*DereferenceAccesses the object pointed to by a pointer

Example: Pointer Operators

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 100;

    int* ptr = &number;

    cout << "Value: " << number << endl;

    cout << "Address: " << &number << endl;

    cout << "Pointer Value: " << *ptr << endl;

    return 0;
}

Example Output:

main.cpp
Run Online
Value: 100
Address: (memory address)
Pointer Value: 100

The actual memory address will vary each time the program runs.

Practical Uses of Pointer Operators

  • Access objects through memory addresses.

  • Work with dynamically allocated objects.

  • Pass data to functions through pointers.

  • Build linked lists and other data structures.

  • Work with arrays and low-level memory operations.

11. Memory Management Operators in C++

C++ provides new and delete operators for dynamic memory allocation and deallocation.

They allow a program to create objects whose lifetime is managed dynamically.

Memory Management Operators Reference

OperatorPurpose
newAllocates memory and creates an object
deleteDestroys an object and releases its allocated memory
new[]Allocates an array dynamically
delete[]Destroys a dynamically allocated array and releases its memory

Example: Using new and delete

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int* number = new int(100);

    cout << "Value: " << *number << endl;

    delete number;

    return 0;
}

Output:

Example: Using new[] and delete[]

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int* numbers = new int[3]{10, 20, 30};

    for (int i = 0; i < 3; i++) {
        cout << numbers[i] << " ";
    }

    delete[] numbers;

    return 0;
}

Output:

Important: Always release memory allocated using new with the matching delete, and memory allocated using new[] with delete[].

In modern C++, prefer standard containers such as std::vector and smart pointers when they fit your requirements. They help manage object lifetimes automatically.

12. Type and Size Operators in C++

C++ provides operators and language features that help you inspect the size or type information of expressions and objects.

Common Type and Size Operations

Operator or featurePurposeExample
sizeofFinds the size of a type or object in bytessizeof(int)
typeidProvides runtime type informationtypeid(value)
alignofFinds the alignment requirement of a typealignof(double)

sizeof and alignof are language operators. typeid is an operator that requires the <typeinfo> header for its standard declaration.

Example: sizeof Operator

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    cout << "Size of int: " << sizeof(int) << endl;

    cout << "Size of float: " << sizeof(float) << endl;

    cout << "Size of double: " << sizeof(double) << endl;

    cout << "Size of char: " << sizeof(char) << endl;

    return 0;
}

Typical Output:

main.cpp
Run Online
Size of int: 4
Size of float: 4
Size of double: 8
Size of char: 1

Actual sizes depend on the C++ implementation, except that sizeof(char) is always 1 byte.

Complete C++ Program Using Different Operators

Now let's combine several common operators in one program.

C++ Code

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 10;
    int b = 5;

    // Arithmetic operator
    cout << "Addition: " << a + b << endl;

    // Relational operator
    cout << "Greater: " << (a > b) << endl;

    // Logical operator
    cout << "Logical: " << (a > 5 && b < 10) << endl;

    // Assignment operator
    a += 5;
    cout << "Updated A: " << a << endl;

    // Increment operator
    ++a;
    cout << "Incremented A: " << a << endl;

    // Bitwise operator
    cout << "Bitwise AND: " << (a & b) << endl;

    // Conditional operator
    cout << "Result: " << (a > b ? "Greater" : "Smaller") << endl;

    return 0;
}

Output

main.cpp
Run Online
Addition: 15
Greater: 1
Logical: 1
Updated A: 15
Incremented A: 16
Bitwise AND: 0
Result: Greater

Explanation

This program demonstrates several operator categories:

  • Arithmetic operators calculate the sum.

  • Relational operators compare two numbers.

  • Logical operators check multiple conditions.

  • Assignment operators update variable values.

  • Increment operators increase a variable by one.

  • Bitwise operators work with individual bits.

  • Conditional operators select a result based on a condition.

Operator Precedence and Associativity in C++

When an expression contains multiple operators, C++ follows specific rules to determine how operators are grouped.

These rules are called operator precedence and associativity.

What Is Operator Precedence?

Operator precedence determines which operators are grouped first in an expression.

For example:

Multiplication has higher precedence than addition.

Therefore, the expression is grouped as:

What Is Operator Associativity?

Associativity determines how operators with the same precedence are grouped.

For example:

Subtraction has left-to-right associativity.

Therefore:

Common Operator Precedence Reference

PriorityOperatorsAssociativity
Highest()[].->Left to right
++--!~ unary +-Right to left
*/%Left to right
+-Left to right
<<>>Left to right
<<=>>=Left to right
==!=Left to right
&^ ``Left to right
&& ``Left to right
?:Right to left
Assignment operatorsRight to left
Lowest,Left to right

This is a simplified reference. The exact precedence table includes additional operators and distinctions between different operator forms.

Tip: Use parentheses when writing complex expressions. They make your intentions clear and help prevent mistakes.

Common Mistakes When Using C++ Operators

Beginners often make small mistakes when working with operators. Here are some common problems to avoid.

1. Confusing = and ==

Incorrect:

main.cpp
Run Online
if (a = 10) {
    cout << "Equal";
}

Correct:

main.cpp
Run Online
if (a == 10) {
    cout << "Equal";
}

Use = for assignment and == for comparison.

2. Confusing && and &

&& is a logical AND operator, while & is a bitwise AND operator.

They perform different operations.

3. Ignoring Integer Division

Example:

The result is 3 because both operands are integers.

Use 10.0 / 3 when you need a decimal result.

4. Using the Modulus Operator With Floating-Point Values

The % operator is used with integral operands, not floating-point operands.

For floating-point remainder calculations, use std::fmod() from the <cmath> header.

5. Incorrect Use of Increment Operators

Avoid expressions that modify the same variable multiple times without proper sequencing.

For example, avoid:

Such expressions can have undefined behaviour because the modifications are not properly sequenced.

Use separate statements instead.

6. Forgetting to Release Dynamically Allocated Memory

If you use new, ensure that the allocated object is properly destroyed with delete, or use a suitable smart pointer.

For arrays allocated with new[], use delete[].

Best Practices for Using Operators in C++

Follow these simple practices when writing C++ programs:

  • Choose the correct operator for each operation.

  • Use parentheses to make complex expressions easier to understand.

  • Use == for comparison and = for assignment.

  • Understand the difference between logical and bitwise operators.

  • Avoid complicated expressions with multiple side effects.

  • Check for division by zero.

  • Use appropriate data types for mathematical calculations.

  • Prefer standard containers and smart pointers for safer memory management.

  • Avoid unnecessary pointer manipulation.

  • Write clear and readable expressions.

Frequently Asked Questions About C++ Operators

1. What are operators in C++?

Operators are symbols or keywords used to perform operations on values and variables. Examples include +, -, *, /, ==, and &&.

2. How many types of operators are there in C++?

C++ has several operator categories, including arithmetic, relational, logical, assignment, increment and decrement, bitwise, conditional, comma, pointer, and member access operators.

3. What are arithmetic operators in C++?

Arithmetic operators perform mathematical calculations. The main arithmetic operators are +, -, *, /, and %.

4. What are relational operators in C++?

Relational operators compare two values and return a Boolean result. Examples include ==, !=, >, <, >=, and <=.

5. What are logical operators in C++?

Logical operators combine or reverse conditions. C++ provides && for AND, || for OR, and ! for NOT.

6. What is the difference between = and == in C++?

= assigns a value to a variable, while == checks whether two values are equal.

7. What is the conditional operator in C++?

The conditional operator ?: selects one of two expressions depending on whether a condition is true or false.

8. What are bitwise operators in C++?

Bitwise operators perform operations on the individual bits of integer values. Examples include &, |, ^, ~, <<, and >>.

9. What is the sizeof operator in C++?

The sizeof operator returns the size of a type or object in bytes.

10. What is the difference between prefix and postfix increment?

Prefix increment (++a) increases the variable before its updated value is used. Postfix increment (a++) produces the original value before increasing the variable.

11. What is operator precedence in C++?

Operator precedence determines how operators are grouped when an expression contains multiple operators.

12. Can operators be overloaded in C++?

Yes. C++ allows programmers to define how many existing operators behave with user-defined types through operator overloading. However, not every operator can be overloaded, and operator overloading cannot change an operator's precedence or associativity.

Runnable Code Example: C++ Operators Reference

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <compare>

struct PacketHeader {
    int sequenceNumber;
    int priority;

    // C++20 Spaceship Operator for automatic 3-way comparisons
    auto operator<=>(const PacketHeader&) const = default;
};

int main() {
    int a = 12; // 0000 1100
    int b = 25; // 0001 1001

    std::cout << "Bitwise AND (a & b): " << (a & b) << "
";
    std::cout << "Bitwise OR  (a | b): " << (a | b) << "
";
    std::cout << "Bitwise XOR (a ^ b): " << (a ^ b) << "
";
    std::cout << "Shift Left  (a << 2): " << (a << 2) << "
";

    // Ternary operator
    int maxVal = (a > b) ? a : b;
    std::cout << "Max value: " << maxVal << "
";

    // Spaceship operator
    PacketHeader p1{101, 1};
    PacketHeader p2{102, 1};
    if (p1 < p2) {
        std::cout << "Packet 1 has lower sequence than Packet 2
";
    }
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is the C++20 three-way comparison (spaceship operator <=>) operator?

A: The `<=>` operator compares two objects in a single expression, returning `std::strong_ordering`, `std::weak_ordering`, or `std::partial_ordering` (less, equal, greater). Declaring it `= default` auto-generates all 6 relational operators (`<`, `<=`, `>`, `>=`, `==`, `!=`).
Q

Q: Why should parentheses be used even when operator precedence is known?

A: Complex operator interactions (such as bitwise operators mixed with comparisons) can lead to subtle bugs and reduce readability for teammates.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use explicit parentheses to make complex mathematical or bitwise expressions unambiguous.
2. Adopt the C++20 default spaceship operator <=> to implement complete class comparisons with minimal boilerplate.
3. Do not overload logical operators (&&, ||, ,) as custom overloads lose short-circuit evaluation semantics.