## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

### 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

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required