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. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>15.3: Operations on Structures
</title>
10 <link href=
"sx1b.html" rev=precedes
>
11 <link href=
"sx1d.html" rel=precedes
>
12 <link href=
"sx1.html" rev=subdocument
>
15 <H2>15.3: Operations on Structures
</H2>
17 <p>[This section corresponds roughly to K
&R Sec.
6.2]
18 </p><p>There is a relatively small number of operations
19 which C directly supports on structures.
20 As we've seen, we can define structures,
21 declare variables of structure type,
22 and select the members of structures.
23 We can also assign entire structures:
28 would assign
<em>all
</em> of
<TT>c2
</TT> to
<TT>c1
</TT>
29 (both the real and imaginary parts,
30 assuming the preceding declarations).
31 We can also pass structures as arguments to functions,
32 and declare and define functions which return structures.
33 But to do anything else,
34 we typically have to write our own code
36 For example, we could write a function to add two complex numbers:
39 cpx_add(struct complex c1, struct complex c2)
42 sum.real = c1.real + c2.real;
43 sum.imag = c1.imag + c2.imag;
47 We could then say things like
53 you do need a temporary variable like
<TT>sum
</TT>
54 in a function like
<TT>cpx_add
</TT> above that returns a structure.
57 it's possible to couple your own functions to the built-in operators,
58 so that you could write
<TT>c1 = c2 + c2
</TT>
59 and have it call your complex add function.)
60 </p><p>One more thing you can do with a structure is
61 initialize a structure variable while declaring it.
62 As for array initializations,
64 the initializer consists of
65 a comma-separated list of values enclosed in braces
<TT>{}
</TT>:
67 struct complex c1 = {
1,
2};
68 struct complex c2 = {
3,
4};
71 the type of each initializer in the list
72 must be compatible with the type of the corresponding structure member.
76 <a href=
"sx1b.html" rev=precedes
>prev
</a>
77 <a href=
"sx1d.html" rel=precedes
>next
</a>
78 <a href=
"sx1.html" rev=subdocument
>up
</a>
79 <a href=
"top.html">top
</a>
82 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
83 //
<a href=
"copyright.html">Copyright
</a> 1996-
1999
84 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>