7.1 Assignment Operators

[This section corresponds to K&R Sec. 2.10]

The first and more general way is that any time you have the pattern

	v = v op e
where v is any variable (or anything like a[i]), op is any of the binary arithmetic operators we've seen so far, and e is any expression, you can replace it with the simplified
	v op= e
For example, you can replace the expressions
	i = i + 1
	j = j - 10
	k = k * (n + 1)
	a[i] = a[i] / b
with
	i += 1
	j -= 10
	k *= n + 1
	a[i] /= b

In an example in a previous chapter, we used the assignment

	a[d1 + d2] = a[d1 + d2] + 1;
to count the rolls of a pair of dice. Using +=, we could simplify this expression to
	a[d1 + d2] += 1;

As these examples show, you can use the ``op='' form with any of the arithmetic operators (and with several other operators that we haven't seen yet). The expression, e, does not have to be a constant like 1; it can be any expression. You don't always need as many explicit parentheses when using the op= operators: the expression

	k *= n + 1
is interpreted as
	k = k * (n + 1)


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995-1997 // mail feedback