* remove "\r" nonsense
[mascara-docs.git] / C / the.ansi.c.programming.language / c.programming.notes / sx7a.html
blob37689f092c1bb55a833f0123c7dad560fb8bf2e8
1 <!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
5 <html>
6 <head>
7 <link rev="owner" href="mailto:scs@eskimo.com">
8 <link rev="made" href="mailto:scs@eskimo.com">
9 <title>7.1 Assignment Operators</title>
10 <link href="sx7.html" rev=precedes>
11 <link href="sx7b.html" rel=precedes>
12 <link href="sx7.html" rev=subdocument>
13 </head>
14 <body>
15 <H2>7.1 Assignment Operators</H2>
17 <p>[This section corresponds to K&amp;R Sec. 2.10]
18 </p><p>The first and more general way is that any time you have the
19 pattern
20 <pre>
21 <I>v</I> = <I>v</I> <I>op</I> <I>e</I>
22 </pre>
23 where <I>v</I> is any variable
24 (or anything like <TT>a[i]</TT>),
25 <I>op</I> is any of the binary arithmetic operators we've seen so far,
27 and <I>e</I> is any expression,
28 you can replace it with the simplified
29 <pre>
30 <I>v</I> <I>op</I>= <I>e</I>
31 </pre>
32 For example, you can replace the expressions
33 <pre>
34 i = i + 1
35 j = j - 10
36 k = k * (n + 1)
37 a[i] = a[i] / b
38 </pre>
39 with
40 <pre>
41 i += 1
42 j -= 10
43 k *= n + 1
44 a[i] /= b
45 </pre>
46 </p><p>In an example in a previous chapter,
47 we used the assignment
48 <pre>
49 a[d1 + d2] = a[d1 + d2] + 1;
50 </pre>
51 to count the rolls of a pair of dice.
52 Using <TT>+=</TT>, we could simplify this expression to
53 <pre>
54 a[d1 + d2] += 1;
55 </pre>
56 </p><p>As these examples show,
57 you can
58 use the ``op='' form
59 with any of the arithmetic operators
60 (and with several other operators that we haven't seen yet).
61 The expression, <I>e</I>,
62 does not have to be the constant 1;
63 it can be any expression.
64 You don't always need as many explicit parentheses
65 when using the <I>op</I><TT>=</TT> operators:
66 the expression
67 <pre>
68 k *= n + 1
69 </pre>
70 is interpreted as
71 <pre>
72 k = k * (n + 1)
73 </pre>
75 </p><hr>
76 <p>
77 Read sequentially:
78 <a href="sx7.html" rev=precedes>prev</a>
79 <a href="sx7b.html" rel=precedes>next</a>
80 <a href="sx7.html" rev=subdocument>up</a>
81 <a href="top.html">top</a>
82 </p>
83 <p>
84 This page by <a href="http://www.eskimo.com/~scs/">Steve Summit</a>
85 // <a href="copyright.html">Copyright</a> 1995-1997
86 // <a href="mailto:scs@eskimo.com">mail feedback</a>
87 </p>
88 </body>
89 </html>