- [Instructor] C++ supports compound assignment operators
that allow you to combine an assignment
with an arithmetic operation in one operator.
These are both convenient and efficient.
So let's start out by declaring some variables here,
and we'll print them.
And when I build and run that
we get the result that we expect.
So now let's try out a compound assignment operator,
I'll say, Y + = X.
What this'll do, is it will take the value of X,
which is five,
add it to the value of Y which is 47
and leave that result in Y
without doing any copy operation.
So, when I build and run this, you see that Y is now 52.
This works for subtraction,
works for division,
which is integer division.
So it has a remainder and that's what
the modulus operator get the remainder.
And of course it works for multiplication.
There's one important distinction between a compound
assignment and its equivalent expression.
If I were to say, Y = Y + X,
and I build and run that, you get the same end result
as with the compound operator.
The difference is, is that now both X and Y
are evaluated on this side
and Y is evaluated again on the other side
of the assignment operator.
So Y is actually evaluated twice.
And with the compound operator,
Y is only evaluated once and you get the same result.
Now, there are circumstances where this makes a difference,
especially when using objects.
And we'll see some examples later on, but in general,
the compound assignment operators are convenient, safe,
often more efficient than their common equivalents.
So feel free to use them wherever you would use the
equivalent expression, just be aware of the distinctions.