Assignment operators are used to assign values to variables. In C++, apart from the basic assignment operator (=
), there are several compound assignment operators that combine arithmetic operations with assignment.
=
: Assign+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign%=
: Modulus and assign
The =
operator assigns the value on its right to the variable on its left.
int a;
a = 5; // a is now 5
The +=
operator adds the value on its right to the variable on its left and then assigns the result to the variable on the left.
int a = 5;
a += 3; // a is now 8
The -=
operator subtracts the value on its right from the variable on its left and then assigns the result to the variable on the left.
int a = 5;
a -= 3; // a is now 2
The *=
operator multiplies the variable on its left by the value on its right and then assigns the result to the variable on the left.
int a = 5;
a *= 3; // a is now 15
The /=
operator divides the variable on its left by the value on its right and then assigns the result to the variable on the left.
int a = 15;
a /= 3; // a is now 5
The %=
operator calculates the modulus of the variable on its left by the value on its right and then assigns the result to the variable on the left.
int a = 15;
a %= 4; // a is now 3
Assignment operators in C++ simplify code by combining arithmetic operations with assignment. They are a shorthand way of performing operations and then storing the result in the same variable. Practice using these operators to become more familiar with their functionality.