I just realized that I was using =+
instead of the operator +=
and my program was doing all sorts of weird and unexpected things.
Eclipse didn't give me an error of any kind so I assume that =+
is a legitimate operator, but there is no reference to that in my book.
My question is:
What does =+
do and under what circumstances would you use it?
Best Answer
A common syntax is:
This is the add and assignment operator, which adds right-hand expression to the left-hand variable then assigns the result to left-hand variable. For example:
A far less common syntax is:
Usually this is written as two different operators, separated by a space:
Without the space, it looks as follows:
An idiomatic way to write this is to shift the unary operator to the right-hand side:
Now it's easy to see that
i
is being assigned to the positive value ofj
. However,+
is superfluous, so it's often dropped, resulting ini = j
, effectively the equivalent ofi = +1 * j
. In contrast is the negative unary operator:Here, the
-
would be necessary because it inverts the signedness ofj
, effectively the equivalent ofi = -1 * j
.See the operators tutorial for more details.