🔹 Operators in C++
Operators are symbols that perform operations on variables and values.
For example:
int a = 10, b = 5;
cout << a + b; // + is an operator (Addition)
C++ operators are mainly divided into categories:
1. Arithmetic Operators
Used for mathematical operations.
| Operator | Meaning | Example |
+ | Addition | a + b = 15 |
- | Subtraction | a - b = 5 |
* | Multiplication | a * b = 50 |
/ | Division | a / b = 2 |
% | Modulus (Remainder) | a % b = 0 |
2. Relational (Comparison) Operators
Used to compare two values.
They return true (1) or false (0).
| Operator | Meaning | Example |
== | Equal to | a == b → false |
!= | Not equal to | a != b → true |
> | Greater than | a > b → true |
< | Less than | a < b → false |
>= | Greater than or equal to | a >= b → true |
<= | Less than or equal to | a <= b → false |
3. Logical Operators
Used for decision making (conditions).
| Operator | Meaning | Example | ||||
&& | Logical AND (true if both are true) | (a > 5 && b > 2) → true | ||||
| ` | ` | Logical OR (true if at least one is true) | `(a > 5 | b > 10) → true` | ||
! | Logical NOT (reverses result) | !(a > b) → false |
4. Assignment Operators
Used to assign values.
| Operator | Meaning | Example |
= | Assigns value | x = 10 |
+= | Adds and assigns | x += 5; // x = x + 5 |
-= | Subtract and assign | x -= 5; |
*= | Multiply and assign | x *= 2; |
/= | Divide and assign | x /= 2; |
%= | Modulus and assign | x %= 2; |
5. Increment and Decrement Operators
Change the value by +1 or -1.
| Operator | Meaning | Example |
++ | Increment by 1 | ++a; (pre-increment) / a++; (post-increment) |
-- | Decrement by 1 | --a; / a--; |
6. Bitwise Operators
Work at the bit level (used in low-level programming).
| Operator | Meaning | Example (a=5=0101, b=3=0011) | ||
& | AND | a & b = 1 (0001) | ||
| ` | ` | OR | `a | b = 7` (0111) |
^ | XOR | a ^ b = 6 (0110) | ||
~ | NOT (1’s complement) | ~a = -6 | ||
<< | Left shift | a << 1 = 10 (1010) | ||
>> | Right shift | a >> 1 = 2 (0010) |
7. Conditional (Ternary) Operator
Shorthand for if-else.
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
8. Comma Operator
Used to separate multiple expressions, returns the last value.
int x = (5, 10); // x = 10
9. sizeof Operator
Gives size of a data type in bytes.
cout << sizeof(int); // 4
10. Pointer Operators
Used with pointers.
| Operator | Meaning | Example |
& | Address-of operator | &a gives address of a |
* | Dereference operator | *ptr gives value stored at pointer |
✅ Example program using multiple operators:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
cout << "Arithmetic: " << a + b << endl;
cout << "Relational: " << (a > b) << endl;
cout << "Logical: " << (a > 0 && b > 0) << endl;
cout << "Assignment: " << (a += 2) << endl;
cout << "Bitwise AND: " << (a & b) << endl;
cout << "Sizeof int: " << sizeof(int) << endl;
return 0;
}