2.7. The op= Operators
The op= operators are used in statements of the form
lhs op= rhs;
where op can be any of the arithmetic operators +, −, *, /, %. It also works with some other operators you haven't seen yet. The preceding statement is basically a shorthand representation of the statement
lhs = lhs op (rhs);
The right-hand side (rhs) is in brackets because it is worked out first—then the result is combined with the left-hand side (lhs) using the operation op. Let's look at a few examples of this to make sure it's clear. To increment an int variable count by 5 you can write:
count += 5;
This has the same effect as the statement:
count = count + 5;
Of course, the expression to the right of the op= operator can be anything that is legal in the context, so the statement:
result /= a % b/(a + b);
is equivalent to:
result = result/(a % b/(a + b));
What I have said so far about op= operations is not quite the whole story. If the type of the result of the rhs expression is different from the type of lhs, the compiler will automatically insert a cast to convert the rhs value to the same type as lhs. This would happen with the last example if result was of type int and a and b were of type double, for example. This is quite different from the way the normal assignment operation is treated. A statement using the op= operator is really equivalent to:
lhs = (type_of_lhs)(lhs op (rhs));
The automatic conversion will be inserted by the compiler regardless of what the types of lhs and
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access