Node:More Special Assignments, Next:Comparisons and logic, Previous:Special Assignment Operators ++ --, Up:Expressions and operators
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:
variable1 = variable1 + variable2; variable1 += variable2;
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:
+=
-=
*=
/=
%=
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:
#include <stdio.h> int main() { int my_int; printf ("Assignment Operators:\n\n"); my_int = 10; /* Assignment */ printf ("my_int = 10 : %d\n",my_int); my_int++; /* my_int = my_int + 1 */ printf ("my_int++ : %d\n",my_int); my_int += 5; /* my_int = my_int + 5 */ printf ("my_int += 5 : %d\n",my_int); my_int--; /* my_int = my_int = 1 */ printf ("my_int-- : %d\n",my_int); my_int -= 2; /* my_int = my_int - 2 */ printf ("my_int -= 2 : %d\n",my_int); my_int *= 5; /* my_int = my_int * 5 */ printf ("my_int *= 5 : %d\n",my_int); my_int /= 2; /* my_int = my_int / 2 */ printf ("my_int /= 2 : %d\n",my_int); my_int %= 3; /* my_int = my_int % 3 */ printf ("my_int %%= 3 : %d\n",my_int); return 0; }
The program above produces the output below:
Assignment Operators: my_int = 10 : 10 my_int++ : 11 my_int += 5 : 16 my_int-- : 15 my_int -= 2 : 13 my_int *= 5 : 65 my_int /= 2 : 32 my_int %= 3 : 2
The second to last line of output is
my_int /= 2 : 32
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.