Operators in C++ are symbols that perform specific operations on operands (values or variables). They are essential for building expressions and controlling the flow of your program.
Types of Operators
Arithmetic Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Relational Operators:
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Logical Operators:
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
Bitwise Operators:
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left shift (<<)
Right shift (>>)
Assignment Operators:
Assignment (=)
Addition assignment (+=)
Subtraction assignment (-=)
Multiplication assignment (*=)
Division assignment (/=)
Modulus assignment (%=)
Bitwise AND assignment (&=)
Bitwise OR assignment (|=)
Bitwise XOR assignment (^=)
Left shift assignment (<<=)
Right shift assignment (>>=)
Conditional Operator:
Ternary operator (? :)
Member Access Operators:
Dot operator (.)
Arrow operator (->)
Increment/Decrement Operators:
Pre-increment (++)
Post-increment (++)
Pre-decrement (--)
Post-decrement (--)
Example Program
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
float c = 3.14;
// Arithmetic operators
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a / b = " << a / b << endl;
cout << "a % b = " << a % b << endl;
// Relational operators
cout << "a == b: " << (a == b) << endl;
cout << "a != b: " << (a != b) << endl;
cout << "a > b: " << (a > b) << endl;
cout << "a < b: " << (a < b) << endl;
cout << "a >= b: " << (a >= b) << endl;
cout << "a <= b: " << (a <= b) << endl;
// Logical operators
bool x = true, y = false;
cout << "x && y: " << (x && y) << endl;
cout << "x || y: " << (x || y) << endl;
cout << "!x: " << !x << endl;
// Conditional operator
int max = (a > b) ? a : b;
cout << "Maximum value: " << max << endl;
// Increment/decrement operators
int i = 5;
cout << "++i: " << ++i << endl;
cout << "i++: " << i++ << endl;
cout << "--i: " << --i << endl;
cout << "i--: " << i-- << endl;
return 0;
}
This program demonstrates the usage of various operators in C++ and their corresponding outputs.
Comments