int a = 10;
int b = 20;
int result = a + b;C++ Operators Reference: Categories, Syntax, and Practical Usage
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:
In this example:
aandbare operands.+is the addition operator.=is the assignment operator.resultstores the calculated value.
Output:
Result: 30Operators 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:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Bitwise operators
Conditional operator
Comma operator
Member access operators
Pointer operators
Memory management operators
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
| Operator | Name | Description | Example |
|---|---|---|---|
+ | Addition | Adds two values | a + b |
- | Subtraction | Subtracts one value from another | a - b |
* | Multiplication | Multiplies two values | a * b |
/ | Division | Divides one value by another | a / b |
% | Modulus | Returns the remainder | a % b |
Example: Arithmetic Operators
#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:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Modulus: 2Practical 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:
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
| Operator | Name | Description | Example |
|---|---|---|---|
== | Equal to | Checks whether values are equal | a == b |
!= | Not equal to | Checks whether values differ | a != b |
> | Greater than | Checks whether the left value is greater | a > b |
< | Less than | Checks whether the left value is smaller | a < b |
>= | Greater than or equal to | Checks whether the left value is greater or equal | a >= b |
<= | Less than or equal to | Checks whether the left value is smaller or equal | a <= b |
Example: Relational Operators
#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:
Equal: false
Not Equal: true
Greater: true
Less: false
Greater or Equal: true
Less or Equal: falsePractical 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
| Operator | Name | Description | Example | ||||
|---|---|---|---|---|---|---|---|
&& | Logical AND | True when both conditions are true | a > 5 && b < 20 | ||||
| ` | ` | Logical OR | True when at least one condition is true | `a > 5 | b < 20` | ||
! | Logical NOT | Reverses a Boolean value | !(a > 5) |
Example: Logical Operators
#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:
true
true
falseExplanation
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
| Operator | Name | Example | Equivalent form | |||
|---|---|---|---|---|---|---|
= | Assignment | a = 10 | Assigns 10 | |||
+= | Addition assignment | a += 5 | a = a + 5 | |||
-= | Subtraction assignment | a -= 5 | a = a - 5 | |||
*= | Multiplication assignment | a *= 2 | a = a * 2 | |||
/= | Division assignment | a /= 2 | a = a / 2 | |||
%= | Modulus assignment | a %= 3 | a = a % 3 | |||
&= | Bitwise AND assignment | a &= 3 | a = a & 3 | |||
| ` | =` | Bitwise OR assignment | `a | = 3` | `a = a | 3` |
^= | Bitwise XOR assignment | a ^= 3 | a = a ^ 3 | |||
<<= | Left shift assignment | a <<= 1 | a = a << 1 | |||
>>= | Right shift assignment | a >>= 1 | a = a >> 1 |
Example: Assignment Operators
#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:
After += : 15
After -= : 12
After *= : 24
After /= : 6Practical 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
| Operator | Name | Description |
|---|---|---|
++a | Prefix increment | Increases the value before using it |
a++ | Postfix increment | Uses the original value before increasing it |
--a | Prefix decrement | Decreases the value before using it |
a-- | Postfix decrement | Uses the original value before decreasing it |
Example: Increment and Decrement
#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:
Original: 10
Prefix Increment: 11
Postfix Increment: 11
After Increment: 12
Prefix Decrement: 11
Postfix Decrement: 11
Final Value: 10Practical 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
| Operator | Name | Description | |
|---|---|---|---|
& | Bitwise AND | Sets a bit when both corresponding bits are 1 | |
| ` | ` | Bitwise OR | Sets a bit when either corresponding bit is 1 |
^ | Bitwise XOR | Sets a bit when corresponding bits differ | |
~ | Bitwise NOT | Inverts the bits | |
<< | Left shift | Shifts bits to the left | |
>> | Right shift | Shifts bits to the right |
Example: Bitwise Operators
#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:
AND: 1
OR: 7
XOR: 6
Left Shift: 10
Right Shift: 2Binary Explanation
The binary representation of 5 is 0101, and the binary representation of 3 is 0011.
| Operation | Binary result | Decimal result | |
|---|---|---|---|
5 & 3 | 0001 | 1 | |
| `5 | 3` | 0111 | 7 |
5 ^ 3 | 0110 | 6 | |
5 << 1 | 1010 | 10 | |
5 >> 1 | 0010 | 2 |
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
condition ? value_if_true : value_if_false;Example: Conditional Operator
#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:
Largest Number: 20Practical 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
expression1, expression2, expression3;Example: Comma Operator
#include <iostream>
using namespace std;
int main() {
int a, b, result;
result = (a = 10, b = 20, a + b);
cout << "Result: " << result;
return 0;
}Output:
Result: 30The 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
| Operator | Name | Purpose |
|---|---|---|
. | Dot operator | Accesses members through an object |
-> | Arrow operator | Accesses members through a pointer |
Example: Dot Operator
#include <iostream>
using namespace std;
class Student {
public:
int age = 20;
};
int main() {
Student s;
cout << "Age: " << s.age;
return 0;
}Output:
Age: 20Example: Arrow Operator
#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:
Age: 20The 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
| Operator | Name | Purpose |
|---|---|---|
& | Address-of | Gets the address of a variable |
* | Dereference | Accesses the object pointed to by a pointer |
Example: Pointer Operators
#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:
Value: 100
Address: (memory address)
Pointer Value: 100The 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
| Operator | Purpose |
|---|---|
new | Allocates memory and creates an object |
delete | Destroys 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
#include <iostream>
using namespace std;
int main() {
int* number = new int(100);
cout << "Value: " << *number << endl;
delete number;
return 0;
}Output:
Value: 100Example: Using new[] and delete[]
#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:
10 20 30Important: 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 feature | Purpose | Example |
|---|---|---|
sizeof | Finds the size of a type or object in bytes | sizeof(int) |
typeid | Provides runtime type information | typeid(value) |
alignof | Finds the alignment requirement of a type | alignof(double) |
sizeof and alignof are language operators. typeid is an operator that requires the <typeinfo> header for its standard declaration.
Example: sizeof Operator
#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:
Size of int: 4
Size of float: 4
Size of double: 8
Size of char: 1Actual 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
#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
Addition: 15
Greater: 1
Logical: 1
Updated A: 15
Incremented A: 16
Bitwise AND: 0
Result: GreaterExplanation
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:
int result = 10 + 5 * 2;Multiplication has higher precedence than addition.
Therefore, the expression is grouped as:
10 + (5 * 2)
10 + 10
20What Is Operator Associativity?
Associativity determines how operators with the same precedence are grouped.
For example:
int result = 20 - 5 - 3;Subtraction has left-to-right associativity.
Therefore:
(20 - 5) - 3
15 - 3
12Common Operator Precedence Reference
| Priority | Operators | Associativity | ||
|---|---|---|---|---|
| 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 operators | Right 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:
if (a = 10) {
cout << "Equal";
}Correct:
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:
int result = 10 / 3;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:
int result = a++ + ++a;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#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 PrepQ: What is the C++20 three-way comparison (spaceship operator <=>) operator?
Q: Why should parentheses be used even when operator precedence is known?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
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.