0% found this document useful (0 votes)
32 views

7 - 1 Assignment Operators

This document discusses assignment operators in C that allow simplifying expressions like v = v op e to the form v op= e. It provides examples like replacing i = i + 1 with i += 1. It notes the expression e can be any expression, not just the constant 1, and parentheses aren't always needed with op= operators as k *= n + 1 is interpreted as k = k * (n + 1). Assignment operators can be used with any arithmetic operators and some others not discussed yet.

Uploaded by

gdskumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

7 - 1 Assignment Operators

This document discusses assignment operators in C that allow simplifying expressions like v = v op e to the form v op= e. It provides examples like replacing i = i + 1 with i += 1. It notes the expression e can be any expression, not just the constant 1, and parentheses aren't always needed with op= operators as k *= n + 1 is interpreted as k = k * (n + 1). Assignment operators can be used with any arithmetic operators and some others not discussed yet.

Uploaded by

gdskumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

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 the constant 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)

You might also like