Assignment operators in C++ allow us to assign values to variables.
The most common assignment operator is the operator =
. This operator is used to assign the value on the right to the variable on the left.
In addition to the basic assignment operator (=
), there are compound assignment operators that combine an arithmetic operation with assignment, simplifying and optimizing the code.
If you want to learn more about Assignment Operators
check the Introduction to Programming Course read more
Basic assignment operator (=
)
Assignment (=
)
The basic assignment operator (=
) is used to assign a value to a variable. For example:
int a = 5; // Assigns the value 5 to the variable a
The assignment operator is also used to update the value of a variable. For example:
int a = 5; // Initial assignment
a = 10; // Value update
Do not confuse the assignment operator =
with the equality comparator ==
Compound assignment operators
Add and assign (+=
)
The operator +=
adds a value to a variable and assigns the result to that variable. For example:
int a = 5;
a += 3; // a is now 8 (equivalent to a = a + 3)
Subtract and assign (-=
)
The operator -=
subtracts a value from a variable and assigns the result to that variable. For example:
int a = 10;
a -= 3; // a is now 7 (equivalent to a = a - 3)
Multiply and assign (*=
)
The operator *=
multiplies a variable by a value and assigns the result to that variable. For example:
int a = 4;
a *= 6; // a is now 24 (equivalent to a = a * 6)
Divide and assign (/=
)
The operator /=
divides a variable by a value and assigns the result to that variable. For example:
int a = 20;
a /= 4; // a is now 5 (equivalent to a = a / 4)
Modulus and assign (%=
)
The operator %=
calculates the modulus of a variable by a value and assigns the result to that variable. For example:
int a = 17;
a %= 5; // a is now 2 (equivalent to a = a % 5)
Operator precedence
It is important to remember that assignment operators have a lower precedence than most other operators in C++. Therefore, expressions on the right side of assignment operators are evaluated first.
For example:
int a = 5;
int b = 10;
a += b * 2; // a is now 25 (b * 2 is evaluated first, then a += 20)