Assignment Operators and Expressions:
Expressions such as
i = i + 2;
in which the variable on the left hand side is repeated immediately on the right can be written in the compressed form.
i += 2
The operator +- is called an assignment operator.
we don't ``evaluate'' the i on the left hand side of the = at all, we assign to it. The distinction becomes important, however, when the left hand side (expr<sub>1</sub>) is more complicated than a simple variable. For example, we could add 2 to each of the n cells of an array a with code like
int i = 0;
while(i < n)
a[i++] += 2;
If we tried to use the expanded form, we'd get
int i = 0;
while(i < n)
a[i++] = a[i++] + 2;
and by trying to increment i twice within the same expression we'd get (as we'll see) undesired, unpredictable, and in fact undefined results. (Of course, a more natural form of this loop would be
for(i = 0; i < n; i++)
a[i] += 2;
and with the increment of i moved out of the array subscript, it wouldn't matter so much whether we used a[i] += 2 or a[i] = a[i] + 2.)
Most binary operators (operators like + that have a left and right operand ) have a corresponding assignment operator op =, where op is one of
+ - * / % << >> & ^ |
If expr1 and expr2 are expressions, then
expr1 op = expr2
eg,
int bitcount (unsigned x)
{
int b;
for ( b=0; x != 0; x>>=1)
if ( x & 01)
b++;
return b;
}