Operators in C++

Operators in C++ are symbols that instruct the compiler to perform specific operations on operands. They are used to manipulate data and perform calculations in C++ programs. Operators can be categorized into various types based on their functionality, such as arithmetic operators, relational operators, logical operators, etc.

Operators Existence

				
					+---------------------+-------------------+---------------------------------+
|      Category       |       Operator    |          Description            |
+---------------------+-------------------+---------------------------------+
|    Arithmetic       |       +           |   Addition                      |
|                     |       -           |   Subtraction                   |
|                     |       *           |   Multiplication                |
|                     |       /           |   Division                      |
|                     |       %           |   Modulus (Remainder)          |
|                     |       ++          |   Increment                    |
|                     |       --          |   Decrement                    |
+---------------------+-------------------+---------------------------------+
|    Relational       |       ==          |   Equal to                     |
|                     |       !=          |   Not equal to                 |
|                     |       <           |   Less than                    |
|                     |       >           |   Greater than                 |
|                     |       <=          |   Less than or equal to        |
|                     |       >=          |   Greater than or equal to     |
+---------------------+-------------------+---------------------------------+
|    Logical          |       &&          |   Logical AND                  |
|                     |       ||          |   Logical OR                   |
|                     |       !           |   Logical NOT                  |
+---------------------+-------------------+---------------------------------+
|    Bitwise          |       &           |   Bitwise AND                  |
|                     |       |           |   Bitwise OR                   |
|                     |       ^           |   Bitwise XOR                  |
|                     |       ~           |   Bitwise NOT                  |
|                     |       <<          |   Left shift                   |
|                     |       >>          |   Right shift                  |
+---------------------+-------------------+---------------------------------+
|    Assignment       |       =           |   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       |
|                     |       ++          |   Prefix/postfix increment    |
|                     |       --          |   Prefix/postfix decrement    |
+---------------------+-------------------+---------------------------------+
|    Conditional      |       ?:          |   Ternary conditional operator |
+---------------------+-------------------+---------------------------------+
|    Pointer          |       *           |   Pointer dereference          |
|                     |       &           |   Address-of                   |
|                     |       ->          |   Member selection via pointer |
+---------------------+-------------------+---------------------------------+
|    Others           |       sizeof      |   Size of object or type       |
|                     |       ,           |   Comma operator               |
+---------------------+-------------------+---------------------------------+

				
			

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on operands. C++ supports several arithmetic operators:

  1. Addition (+): Adds two operands.
  2. Subtraction (-): Subtracts the second operand from the first.
  3. Multiplication (*): Multiplies two operands.
  4. Division (/): Divides the first operand by the second.
  5. Modulus (%): Computes the remainder of the division of the first operand by the second.
				
					#include <iostream>

int main() {
    int a = 10, b = 4;
    int sum = a + b;
    int difference = a - b;
    int product = a * b;
    int quotient = a / b;
    int remainder = a % b;

    std::cout << "Sum: " << sum << std::endl;
    std::cout << "Difference: " << difference << std::endl;
    std::cout << "Product: " << product << std::endl;
    std::cout << "Quotient: " << quotient << std::endl;
    std::cout << "Remainder: " << remainder << std::endl;

    return 0;
}

				
			
				
					// output //
Sum: 14
Difference: 6
Product: 40
Quotient: 2
Remainder: 2

				
			

In this example, arithmetic operators are used to perform basic mathematical operations on variables a and b.

Relational Operators

Relational operators are used to compare the relationship between two operands. They return a Boolean value indicating whether the comparison is true or false.

  1. Equal to (==): Checks if two operands are equal.
  2. Not equal to (!=): Checks if two operands are not equal.
  3. Greater than (>): Checks if the first operand is greater than the second.
  4. Less than (<): Checks if the first operand is less than the second.
  5. Greater than or equal to (>=): Checks if the first operand is greater than or equal to the second.
  6. Less than or equal to (<=): Checks if the first operand is less than or equal to the second.
				
					#include <iostream>

int main() {
    int x = 5, y = 10;

    std::cout << "x == y: " << (x == y) << std::endl;
    std::cout << "x != y: " << (x != y) << std::endl;
    std::cout << "x > y: " << (x > y) << std::endl;
    std::cout << "x < y: " << (x < y) << std::endl;
    std::cout << "x >= y: " << (x >= y) << std::endl;
    std::cout << "x <= y: " << (x <= y) << std::endl;

    return 0;
}

				
			
				
					// output //
x == y: 0
x != y: 1
x > y: 0
x < y: 1
x >= y: 0
x <= y: 1

				
			

These examples demonstrate the use of relational operators to compare variables x and y.

Logical Operators

Logical operators are used to perform logical operations on Boolean operands. They return a Boolean value as the result of the operation.

  1. Logical AND (&&): Returns true if both operands are true.
  2. Logical OR (||): Returns true if at least one of the operands is true.
  3. Logical NOT (!): Returns true if the operand is false and vice versa.
				
					#include <iostream>

int main() {
    bool x = true, y = false;

    std::cout << "x && y: " << (x && y) << std::endl;
    std::cout << "x || y: " << (x || y) << std::endl;
    std::cout << "!x: " << (!x) << std::endl;

    return 0;
}

				
			
				
					// output //
x && y: 0
x || y: 1
!x: 0

				
			

These examples demonstrate the use of logical operators to perform logical operations on Boolean variables x and y.

Assignment Operators

Assignment operators are used to assign values to variables. They combine the operation of assigning a value with another operation, such as addition, subtraction, multiplication, etc.

  1. Assignment (=): Assigns the value of the right operand to the left operand.
  2. Addition assignment (+=): Adds the value of the right operand to the left operand and assigns the result to the left operand.
  3. Subtraction assignment (-=): Subtracts the value of the right operand from the left operand and assigns the result to the left operand.
  4. Multiplication assignment (*=): Multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.
  5. Division assignment (/=): Divides the value of the left operand by the value of the right operand and assigns the result to the left operand.
  6. Modulus assignment (%=): Computes the modulus of the division of the left operand by the right operand and assigns the result to the left operand.
				
					#include <iostream>

int main() {
    int x = 10, y = 5;

    // Addition assignment
    x += y; // Equivalent to: x = x + y
    std::cout << "x += y: " << x << std::endl;

    // Subtraction assignment
    x -= y; // Equivalent to: x = x - y
    std::cout << "x -= y: " << x << std::endl;

    // Multiplication assignment
    x *= y; // Equivalent to: x = x * y
    std::cout << "x *= y: " << x << std::endl;

    // Division assignment
    x /= y; // Equivalent to: x = x / y
    std::cout << "x /= y: " << x << std::endl;

    // Modulus assignment
    x %= y; // Equivalent to: x = x % y
    std::cout << "x %= y: " << x << std::endl;

    return 0;
}

				
			
				
					// output //
x += y: 15
x -= y: 10
x *= y: 50
x /= y: 10
x %= y: 0

				
			

These examples demonstrate the use of assignment operators to perform operations on variables x and y while assigning the result to x.

Bitwise Operators

Bitwise operators are used to perform bitwise operations on integer operands. They manipulate individual bits of operands.

  1. Bitwise AND (&): Performs a bitwise AND operation.
  2. Bitwise OR (|): Performs a bitwise OR operation.
  3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
  4. Bitwise NOT (~): Performs a bitwise NOT (one’s complement) operation.
  5. Left shift (<<): Shifts the bits of the left operand to the left by a specified number of positions.
  6. Right shift (>>): Shifts the bits of the left operand to the right by a specified number of positions.
				
					#include <iostream>

int main() {
    int x = 5, y = 3;

    std::cout << "x & y: " << (x & y) << std::endl;
    std::cout << "x | y: " << (x | y) << std::endl;
    std::cout << "x ^ y: " << (x ^ y) << std::endl;
    std::cout << "~x: " << (~x) << std::endl;
    std::cout << "x << 1: " << (x << 1) << std::endl;
    std::cout << "x >> 1: " << (x >> 1) << std::endl;

    return 0;
}

				
			
				
					// output //
x & y: 1
x | y: 7
x ^ y: 6
~x: -6
x << 1: 10
x >> 1: 2

				
			

These examples demonstrate the use of bitwise operators to perform bitwise operations on variables x and y.

Advanced Operators

In addition to the basic operators discussed earlier, C++ also provides some advanced operators that offer powerful functionalities.

The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement. It evaluates a condition and returns one of two expressions based on whether the condition is true or false.

				
					#include <iostream>

int main() {
    int x = 10, y = 20;
    int max = (x > y) ? x : y;

    std::cout << "Max value: " << max << std::endl;

    return 0;
}

				
			
				
					// output //
Max value: 20


				
			

In this example, if the condition (x > y) is true, the value of x is assigned to max; otherwise, the value of y is assigned to max.

Increment (++) Operators

The increment operator (++) increases the value of a variable by 1. It can be used in two forms: pre-increment and post-increment.

Pre-increment (++) Operator: In pre-increment, the value of the variable is incremented before its current value is used in the expression.

				
					int x = 5;
int y = ++x; // Pre-increment

				
			

In this example, x is incremented by 1 before its value is assigned to y. So, y becomes 6 after this operation.

Post-increment (++) Operator: In post-increment, the value of the variable is incremented after its current value is used in the expression.

				
					int x = 5;
int y = x++; // Post-increment

				
			

In this example, the current value of x (which is 5) is assigned to y, and then x is incremented by 1. So, y becomes 5, but x becomes 6 after this operation.

Decrement (–) Operators

The decrement operator (--) decreases the value of a variable by 1. Similar to the increment operator, it can be used in two forms: pre-decrement and post-decrement.

Pre-decrement (–) Operator: In pre-decrement, the value of the variable is decremented before its current value is used in the expression.

				
					int x = 5;
int y = --x; // Pre-decrement

				
			

In this example, x is decremented by 1 before its value is assigned to y. So, y becomes 4 after this operation.

Post-decrement (–) Operator: In post-decrement, the value of the variable is decremented after its current value is used in the expression.

				
					int x = 5;
int y = x--; // Post-decrement

				
			

In this example, the current value of x (which is 5) is assigned to y, and then x is decremented by 1. So, y becomes 5, but x becomes 4 after this operation.

Key Points:

  • Both the increment and decrement operators can be used with variables of integral types (such as int, char, long, etc.) and pointers.
  • Pre-increment/decrement and post-increment/decrement operators can have different behaviors when used in expressions depending on whether the operation occurs before or after the variable is used.
  • Pre-increment/decrement operators are generally more efficient than their post counterparts because they don’t need to create a temporary copy of the variable’s value.

Comma Operator (,)

The comma operator (operator,) in C++ is a binary operator that evaluates two expressions sequentially. It is often misunderstood due to its simplicity, but it serves various purposes in C++ programming.

				
					expr1, expr2

				
			

Here, expr1 and expr2 are expressions separated by a comma.

How the Comma Operator Works:

  1. Evaluation Order: The comma operator evaluates expr1 first, discards its result, and then evaluates expr2, returning the result of expr2.
  2. Sequence of Execution: Both expr1 and expr2 are guaranteed to be evaluated in order from left to right, regardless of their return values. This means expr1 is always evaluated before expr2.

Multiple Statements in a Single Line: The comma operator allows multiple statements to be written on a single line, separating them with commas.

In this example, both a++ and b++ are executed sequentially on the same line.

				
					int a = 5, b = 10; a++, b++;

				
			

For Loop Initialization, Condition, and Increment: The comma operator is often used in the initialization, condition, and increment parts of a for loop.

Here, both i and j are initialized using the comma operator, and the increment and decrement parts of the loop also use the comma operator.

				
					for (int i = 0, j = 10; i < 5; i++, j--) {
    // Loop body
}

				
			

Function Return Values: Although less common, the comma operator can be used to return multiple values from a function.

In this example, the function foo returns the value of y, as it is the rightmost expression separated by a comma.

				
					int foo() {
    int x = 10, y = 20;
    return x, y;
}

				
			

Important Considerations:

  • While the comma operator allows multiple expressions to be evaluated in sequence, only the value of the rightmost expression is considered in most contexts where an expression is expected.
  • The comma operator is primarily used for its side effects, such as incrementing a variable or executing multiple statements in a single line, rather than for its return value.

Code Example

				
					#include <iostream>

int main() {
    int x = 5, y = 10, z;

    z = (x++, y++);
    std::cout << "Value of z: " << z << std::endl; // Output: 10

    return 0;
}

				
			

In this example, the comma operator first evaluates x++, then y++, and returns the value of y++, which is 10. Here value of z is 10 because it is a post increment and first value of y is assigned to z then it is incremented.

Operators in C++ are powerful tools for performing various operations on data and manipulating values. By understanding the different types of operators and their functionalities, you can write more expressive, concise, and efficient code. Practice using operators in different scenarios to become proficient in their usage.Happy coding! ❤️

Table of Contents