C++ Assignment Operators
C++ provides several Assignment Operators to change the value of a variable. These operators are used to modify the value of the left-hand side operand with the value of the right-hand side operand. The assignment operator =
is the most commonly used assignment operator in C++.
Table of Assignment Operators
The table below shows the different assignment operators available in C++
Operator | Name | Description | Example |
---|---|---|---|
= | Simple Assignment | Assigns the value of the right operand to the left operand | a = 7 |
+= | Add and Assignment | Adds the right operand to the left operand and assigns the result to the left operand | a += 7 (equivalent to a = a + 7) |
-= | Subtract and Assignment | Subtracts the right operand from the left operand and assigns the result to the left operand | a -= 7 (equivalent to a = a - 7) |
*= | Multiply and Assignment | Multiplies the right operand with the left operand and assigns the result to the left operand | a *= 7 (equivalent to a = a * 7) |
/= | Divide and Assignment | Divides the left operand by the right operand and assigns the result to the left operand | a /= 7 (equivalent to a = a / 7) |
%= | Modulo and Assignment | Takes the modulo of the left operand by the right operand and assigns the result to the left operand | a %= 7 (equivalent to a = a % 7) |
Example of Assignment Operators
1#include <iostream> 2 3int main() { 4 int a = 5; 5 int b = 2; 6 7 // Simple Assignment 8 a = b; 9 std::cout << "a = " << a << std::endl; // Outputs: a = 2 10 11 // Add and Assignment 12 a += b; 13 std::cout << "a = " << a << std::endl; // Outputs: a = 4 14 15 // Subtract and Assignment 16 a -= b; 17 std::cout << "a = " << a << std::endl; // Outputs: a = 2 18 19 // Multiply and Assignment 20 a *= b; 21 std::cout << "a = " << a << std::endl; // Outputs: a = 4 22 23 // Divide and Assignment 24 a /= b; 25 std::cout << "a = " << a << std::endl; // Outputs: a = 2 26 27 // Modulo and Assignment 28 a %= b; 29 std::cout << "a = " << a << std::endl; // Outputs: a = 0 30 31 return 0; 32}
In the above example, we use different assignment operators to modify the value of the variable a
. The value of a
changes in each step as the assignment operator modifies it with the value of b
.