Operators: Assignment Operators
Learn about the assignment and compound assignment operators in C++ and how to use them.
We'll cover the following
In this lesson, we’ll learn about the C++ assignment operator and the compound assignment operators.
Assignment operator
We use assignment operators to assign values to a variable. We already used the =
operator in several previous lessons.
lvalue and rvalue
The operand on the left side of the assignment operator is usually a modifiable variable, and it is referred to as lvalue. The operand on the right side of the assignment operator is the value or a temporary value of an expression, and it is referred to as rvalue. We use =
to assign a value (on the right side) to the variable (on the left side).
The data types of both the rvalue and the lvalue should always be the same or at least convertible. Otherwise, the compiler will generate a compile-time error.
Compound assignment operator
A compound assignment operator consists of a binary operator and an assignment operator. Its examples include +=
, -=
, /=
, *=
, and so on.
The image below shows the other assignment and compound assignment operators.
Let’s look some of the compound assignment operators now:
-
-=
: Let’s say we have the expression,x -= 2
. It is the same as the expression,x = x - 2
. So, the-=
operator works such that it decrements the current value of the variable (x
) by the right operand (which in this case is2
) and then assigns the updated value to the variable.So, if
x = 4
, thenx -= 2
would bex = 2
. -
+=
: The expression,x += 2
, is the same as the expression,x = x + 2
.So, if
x = 4
, thenx += 2
would bex = 6
. -
*=
: The expression,x *= 2
, is the same as the expression,x = x * 2
.So, if
x = 4
, thenx *= 2
would bex = 8
. -
/=
: The expression,x /= 2
, is the same as the expression,x = x / 2
.So, if
x = 4
, thenx /= 2
would bex = 2
. -
%=
: The expression,x %= 2
, is the same as the expressionx = x % 2
.So, if
x = 5
, thenx %= 2
would bex = 1
.
Look at the table below for more examples.
Compound Assignment Operators
Operators | Meaning | Example |
| Add right operand to left operand and assign to left operand | z += 3 is equivalent to z = z + 3 |
| Subtract right operand to left operand and assign left operand | z -= 3 is equivalent to z = z - 3 |
| Multiply right operand to left operand and assign left operand | z *= 3 is equivalent to z = z * 3 |
| Divide right operand to left operand and assign left operand | z /= 3 is equivalent to z = z / 3 |
| Divide right operand to left operand and assign remainder to left operand | z %= 3 is equivalent to z = z % 3 |