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++

OperatorNameDescriptionExample
=Simple AssignmentAssigns the value of the right operand to the left operanda = 7
+=Add and AssignmentAdds the right operand to the left operand and assigns the result to the left operanda += 7 (equivalent to a = a + 7)
-=Subtract and AssignmentSubtracts the right operand from the left operand and assigns the result to the left operanda -= 7 (equivalent to a = a - 7)
*=Multiply and AssignmentMultiplies the right operand with the left operand and assigns the result to the left operanda *= 7 (equivalent to a = a * 7)
/=Divide and AssignmentDivides the left operand by the right operand and assigns the result to the left operanda /= 7 (equivalent to a = a / 7)
%=Modulo and AssignmentTakes the modulo of the left operand by the right operand and assigns the result to the left operanda %= 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.