The op= operators are used in statements of the form:
lhs op= rhs;
where op can be any of the operators +, -, *, /, %, plus some others you haven't seen yet. The above is basically a shorthand representation of the statement:
lhs = lhs op (rhs);
The right hand side is in brackets because it is worked out first – then the result is combined with the left hand side 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:
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));
You should note that if the type of the result of the rhs expression is different from the type of lhs, the compiler will automatically insert a cast. In the last example, the statement would work with result being of type int and a and b being of type double, for instance. 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)); Of course, this can result in information being lost due to the cast, and you will get no indication that it has occurred.
The complete set of op= operators appears in the precedence table later in this chapter.