Introduction
Operators in C++ are special symbols that perform specific operations on operands. They are the backbone of any computation and logical processing in a program. C++ supports a wide range of operators, enabling developers to manipulate variables and values in various ways. These operators are categorized based on their functionality such as arithmetic, relational, logical, bitwise, assignment, and more. Understanding operators is crucial for writing effective and efficient programs.
A proper grasp of operator precedence and associativity also ensures the correct evaluation of expressions. Below is the complete breakdown of all operators supported in C++ with explanations, general syntax, and examples.
Types of Operators in C++
- Arithmetic Operators:- Used to perform basic arithmetic operations.
Operators: +, -, *, /, %
General Syntax:
result = operand1 operator operand2;
Example:
int a = 10, b = 3;
cout << a + b; // Output: 13
cout << a % b; // Output: 1
- Relational (Comparison) Operators:- Used to compare two values. Returns true or false.
Operators: ==, !=, >, <, >=, <=
Example:
int x = 5, y = 10;
bool result = (x < y); // true
- Logical Operators:- Used to perform logical operations.
Operators: && (AND), || (OR), ! (NOT)
Example:
bool a = true, b = false;
cout << (a && b); // Output: 0
- Assignment Operators:- Used to assign values to variables.
Operators: =, +=, -=, *=, /=, %=
Example:
int a = 10;
a += 5; // a = a + 5 => a = 15
- Increment and Decrement Operators:- Used to increase or decrease a value by 1.
Operators: ++, —
Example:
int a = 5;
a++; // Post-increment: a becomes 6
++a; // Pre-increment: a becomes 7
- Bitwise Operators:- Used for bit-level operations.
Operators: &, |, ^, ~, <<, >>
Example:
int a = 5, b = 3;
cout << (a & b); // Output: 1
- Conditional (Ternary) Operator:- Used as a shorthand for if-else condition.
Syntax: condition ? expression1 : expression2
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
- Comma Operator:- Evaluates two expressions and returns the value of the second.
Example:
int a = (10, 20); // a = 20
- Sizeof Operator:- Returns the size of a data type or variable in bytes.
Example:
cout << sizeof(int); // Typically 4
- Pointer Operators:- Used to work with memory addresses.
Operators: & (address of), * (dereference)
Example:
int a = 5;
int* ptr = &a;
cout << *ptr; // Output: 5
- Scope Resolution Operator (::):- Used to define the scope of variables/functions, especially for global scope.
Example:
int x = 10;
void show() {
int x = 20;
cout << ::x; // Output: 10 (global x)
}
- Member Access Operators:- Used to access members of a class, struct or union.
Operators: . (direct), -> (pointer to member)
Example:
struct Person {
string name;
};
Person p;
p.name = “John”; // using . operator
.Person* ptr = &p;
cout << ptr->name; // using -> operator
- Type Cast Operator:- Used to convert one data type to another.
Syntax: (type) variable
Example:
float f = 3.14;
int a = (int)f; // a = 3