C++ Operators
The operators in C++ are symbols that tell the compiler how to do certain logical or mathematical operations. They are employed to calculate a value from a number of operands. A single literal or variable is the most basic form of an expression, which is made up of one or more operands and, when evaluated, produces a result. Combining operators with operands creates more complex expressions.
C++ contains many built-in operators with distinct meanings when used with built-in types. Many operators are mathematical or logical.
Types of Built-in Operators
Operators can be classified by their operation and operand count. Besides the ternary operator, operators can be unary or binary.
Arithmetic Operators: These compute basic mathematics such as Multiplication, division, addition, subtraction, and % are examples.
- For floating-point variables, the division operator / produces the precise value as expected. When dealing with integers, a / b yields the total number of times b divides a. Only integer types can be used with the % (modulus) operator, which is used to get the residual.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo | a % b (remainder of integer division) |
Example
#include <iostream>
int main() {
int a = 10;
int b = 3;
std::cout << "--- Arithmetic Operators ---" << std::endl;
std::cout << "a + b = " << (a + b) << std::endl; // 13
std::cout << "a - b = " << (a - b) << std::endl; // 7
std::cout << "a * b = " << (a * b) << std::endl; // 30
std::cout << "a / b = " << (a / b) << std::endl; // 3 (integer division)
std::cout << "a % b = " << (a % b) << std::endl; // 1 (remainder)
double x = 10.0;
double y = 3.0;
std::cout << "x / y (double) = " << (x / y) << std::endl; // 3.333...
return 0;
}
Output
--- Arithmetic Operators ---
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
x / y (double) = 3.33333
Relational Operators: These return a true or false bool value after comparing two values. In C++, false is equal to 0 and true is any non-zero number.
- These consist of < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to),!= (not equal to), and == (equal to).
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Example
#include <iostream>
int main() {
int a = 10;
int b = 20;
std::cout << "\n--- Relational Operators ---" << std::endl;
std::cout << "a == b: " << (a == b) << std::endl; // 0 (false)
std::cout << "a != b: " << (a != b) << std::endl; // 1 (true)
std::cout << "a > b: " << (a > b) << std::endl; // 0 (false)
std::cout << "a < b: " << (a < b) << std::endl; // 1 (true)
std::cout << "a >= b: " << (a >= b) << std::endl; // 0 (false)
std::cout << "a <= b: " << (a <= b) << std::endl; // 1 (true)
// Using std::boolalpha for true/false output
std::cout << std::boolalpha;
std::cout << "a == b: " << (a == b) << std::endl; // false
std::cout << std::noboolalpha; // Reset
return 0;
}
Output
--- Relational Operators ---
a == b: 0
a != b: 1
a > b: 0
a < b: 1
a >= b: 0
a <= b: 1
a == b: false
Logical Operators: In addition to returning a bool value, they combine or alter Boolean statements.
- They are || (Logical OR),! (Logical NOT), and && (Logical AND).
- As “short-circuit” operators, && and || only evaluate the right-hand operand when it is required to ascertain the final result.
Operator | Description | Example |
---|---|---|
&& | Logical AND (returns true if both operands are true) | a && b |
|| | Logical OR (returns true if at least one operand is true) | a || b |
! | Logical NOT (inverts the boolean value) | !a |
Example
#include <iostream>
int main() {
bool p = true;
bool q = false;
std::cout << "\n--- Logical Operators ---" << std::endl;
std::cout << std::boolalpha; // For true/false output
std::cout << "p && q: " << (p && q) << std::endl; // false
std::cout << "p || q: " << (p || q) << std::endl; // true
std::cout << "!p: " << (!p) << std::endl; // false
std::cout << "!q: " << (!q) << std::endl; // true
std::cout << std::noboolalpha; // Reset
int x = 5, y = 10, z = 15;
std::cout << "(x < y) && (y < z): " << ((x < y) && (y < z)) << std::endl; // true (1)
std::cout << "(x > y) || (y < z): " << ((x > y) || (y < z)) << std::endl; // true (1)
return 0;
}
Output
--- Logical Operators ---
p && q: false
p || q: true
!p: false
!q: true
(x < y) && (y < z): 1
(x > y) || (y < z): 1
Bitwise Operators: Individual bits can be set and tested since integral operands are treated as collections of bits.
- Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise NOT (~), Left Shift (\<), and Right Shift (>) are among them.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT (one’s complement) | ~a |
<< | Left Shift | a << b |
>> | Right Shift | a >> b |
Example
#include <iostream>
#include <bitset> // For printing binary representation
int main() {
unsigned int a = 5; // Binary: 0101
unsigned int b = 3; // Binary: 0011
std::cout << "\n--- Bitwise Operators ---" << std::endl;
std::cout << "a (0101) & b (0011) = " << (a & b) << " (" << std::bitset<4>(a & b) << ")" << std::endl; // 1 (0001)
std::cout << "a (0101) | b (0011) = " << (a | b) << " (" << std::bitset<4>(a | b) << ")" << std::endl; // 7 (0111)
std::cout << "a (0101) ^ b (0011) = " << (a ^ b) << " (" << std::bitset<4>(a ^ b) << ")" << std::endl; // 6 (0110)
std::cout << "~a (0101) = " << (~a) << " (depends on size, for 4-bit: 1010)" << std::endl; // For unsigned int, this will be a large number
std::cout << "a (0101) << 1 = " << (a << 1) << " (" << std::bitset<4>(a << 1) << ")" << std::endl; // 10 (1010)
std::cout << "a (0101) >> 1 = " << (a >> 1) << " (" << std::bitset<4>(a >> 1) << ")" << std::endl; // 2 (0010)
return 0;
}
Output
--- Bitwise Operators ---
a (0101) & b (0011) = 1 (0001)
a (0101) | b (0011) = 7 (0111)
a (0101) ^ b (0011) = 6 (0110)
~a (0101) = 4294967290 (depends on size, for 4-bit: 1010)
a (0101) << 1 = 10 (1010)
a (0101) >> 1 = 2 (0010)
Assignment Operators: In these, the object represented by the left-hand operand is assigned the value of the right-hand operand.
- = is the straightforward assignment operator.
- Arithmetic or bitwise operations are combined with assignment in compound assignment operators, like +=, -=, *=, /=, %=, &=, |=, ^=, <<=, and >>=.
Operator | Description | Example | Equivalent to |
---|---|---|---|
= | Simple assignment | a = 10 | |
+= | Add and assign | a += b | a = a + b |
-= | Subtract and assign | a -= b | a = a - b |
*= | Multiply and assign | a *= b | a = a * b |
/= | Divide and assign | a /= b | a = a / b |
%= | Modulo and assign | a %= b | a = a % b |
&= | Bitwise AND and assign | a &= b | a = a & b |
|= | Bitwise OR and assign | a |= b | a = a |= b |
^= | Bitwise XOR and assign | a ^= b | a = a ^ b |
<<= | Left shift and assign | a <<= b | a = a << b |
>>= | Right shift and assign | a >> = b | a = a >> b |
Example
#include <iostream>
int main() {
int val = 10;
int x = 5;
std::cout << "\n--- Assignment Operators ---" << std::endl;
std::cout << "Initial val: " << val << std::endl;
val += x; // val = 10 + 5 = 15
std::cout << "val += x: " << val << std::endl;
val -= 3; // val = 15 - 3 = 12
std::cout << "val -= 3: " << val << std::endl;
val *= 2; // val = 12 * 2 = 24
std::cout << "val *= 2: " << val << std::endl;
val /= 4; // val = 24 / 4 = 6
std::cout << "val /= 4: " << val << std::endl;
val %= 5; // val = 6 % 5 = 1
std::cout << "val %= 5: " << val << std::endl;
int bit_val = 8; // 1000
bit_val &= 3; // 1000 & 0011 = 0000 (0)
std::cout << "bit_val &= 3: " << bit_val << std::endl;
return 0;
}
Output
--- Assignment Operators ---
Initial val: 10
val += x: 15
val -= 3: 12
val *= 2: 24
val /= 4: 6
val %= 5: 1
bit_val &= 3: 0
Increment and Decrement Operators: These operators are unary and add or subtract one from their operand.
- Prefix form (++i, –i): The result is the altered object after the operand is increased or decreased. An lvalue is the result.
- Postfix form (i++, i–): Decreases or increases the operand, but the outcome is a duplicate of the original, unaltered value. An rvalue is the result.
Operator | Description | Example |
---|---|---|
++ | Increment (pre-increment: ++a , post-increment: a++ ) | ++a , a++ |
-- | Decrement (pre-decrement: --a , post-decrement: a-- ) | --a , a-- |
Example
#include <iostream>
int main() {
int i = 5;
int j = 5;
int result1, result2;
std::cout << "\n--- Increment/Decrement Operators ---" << std::endl;
// Pre-increment
std::cout << "Initial i: " << i << std::endl; // 5
result1 = ++i; // i becomes 6, then result1 = 6
std::cout << "++i (result1): " << result1 << ", i: " << i << std::endl; // 6, 6
// Post-increment
std::cout << "Initial j: " << j << std::endl; // 5
result2 = j++; // result2 = 5, then j becomes 6
std::cout << "j++ (result2): " << result2 << ", j: " << j << std::endl; // 5, 6
// Similar for decrement
int k = 8;
int l = 8;
std::cout << "Initial k: " << k << std::endl; // 8
result1 = --k; // k becomes 7, then result1 = 7
std::cout << "--k (result1): " << result1 << ", k: " << k << std::endl; // 7, 7
std::cout << "Initial l: " << l << std::endl; // 8
result2 = l--; // result2 = 8, then l becomes 7
std::cout << "l-- (result2): " << result2 << ", l: " << l << std::endl; // 8, 7
return 0;
}
Output
--- Increment/Decrement Operators ---
Initial i: 5
++i (result1): 6, i: 6
Initial j: 5
j++ (result2): 5, j: 6
Initial k: 8
--k (result1): 7, k: 7
Initial l: 8
l-- (result2): 8, l: 7
Other Special Operators:
- Conditional operator (?:): An if-then-else phrase of the form condition provided by a ternary operator? Y: X. X is returned if the condition is true; Y is returned otherwise.
- sizeof operator:: The number of bytes of storage that a type or variable occupies is reported by this compile-time operator.
- Comma operator (,): Left-to-right evaluation of a binary operator. The value of the right-hand operand is the value of the entire expression.
- Member access operators (., ->, .*, ->*): Used to allude to specific union, class, and structure members. For classes that represent iterators and smart pointers, the arrow operator (->) is frequently utilised.
- Function call operator (): When a function name is followed by two brackets (), a function is invoked.
- Subscript operator []: Used to retrieve objects that resemble containers or array elements.
Operator Overloading
The majority of operators can have their meanings redefined in C++ when applied on class-type objects. Operator overloading is the term for this.
Purpose: Because operator overloading enables custom types to behave like built-in types in expressions, it can facilitate the writing and reading of programs.
Mechanism: Operator functions are created in order to overload operators. The operations the overloaded operator will carry out for a certain class are specified by an operator function.
- An operator function’s name is the operator symbol (e.g., operator+ for the + operator) followed by the keyword operator.
- Operator functions can be either non-member (friend) or member functions.
- Member functions: The operand on the left is implicitly bound to this pointer. The right operand for a binary operator is supplied as a single explicit parameter.
- Non-member (friend) functions: Usually, these accept all operands as explicit parameters. An unary operator’s friend function takes one argument, while a binary operator’s buddy function takes two. IO operators (<< and >>) are frequently defined as non-member friend functions because the stream object (std::cout, for example) is the left-hand operand and shouldn’t be changed.
You can also read What Are The Constants In C++ With Code Examples?