Like ++ and --, the following operators are short ways of
writing longer expressions. Consider the following statement:
variable = variable + 23;
In C, this would be a long-winded way of adding 23 to variable. It
could be done more simply with the general increment operator +=, as in
this example:
variable += 23;
This performs exactly the same operation. Similarly, the following two
statements are equivalent:
There are a handful of these operators. For example, one for
subtraction:
variable = variable - 42;
variable -= 42;
More surprisingly, perhaps, there is one for multiplication:
variable = variable * 2;
variable *= 2;
The main arithmetic operators all follow this pattern:
+=
addition assignment operator
-=
subtraction assignment operator
*=
multiplication assignment operator
/=
division assignment operator (floating point and integers)
%=
remainder assignment operator (integers only)
There are more exotic kinds too, used for machine-level operations,
which we will ignore for the moment. (See Advanced operators, if you
want to know more.)
Here is a short program that demonstrates these special assignment operators:
In this example, 65 divided by 2 using the /= operator results in
32, not 32.5. This is because both operands, 65 and 2, are integers,
type int, and when /= operates on two integers, it
produces an integer result. This example only uses integer values,
since that is how the numbers are declared. To get the fractional
answer, you would have had to declare the three numbers involved as
floats.
The last line of output is
my_int %= 3 : 2
This is because 32 divided by 3 is 10 with a remainder of 2.