Previous: 12.5 Common Errors
Up: 12 Structures and Unions
Next: 12.7 Exercises
Previous Page: 12.5 Common Errors
Next Page: 12.7 Exercises

12.6 Summary

In this chapter, we have described the last remaining data types provided by the C language: structures and unions. A structure allows the grouping of various pieces of related information of different types into one variable. It is declared by defining a template specifying the type of each data item stored in the structure and giving each member or field a name:

Variables may be declared when the template is defined or, if a tag is used to name the template, may be declared later using the tag: which allocates storage for all members. Fields of a structure variable may be accessed using the ``dot'' ( .) operator: called qualifying the variable name. Such qualified structure variable expressions may be used like the corresponding field type in a program. Structure variables may be passed to and returned from functions, but it is more common to use pointers to structures to avoid excessive copying. Members of a structure can be accessed with a pointer using the operator:
    _identifiermember_identifier>
which is equivalent to:
  • * <variable_identifier>).<member_identifier>

We have illustrated the use of structures with various programming examples.

Finally, we have described the union data type, which is defined similar to structures; however, has the semantics of only one of the member types being resident in such a variable at one time. That is, a union allows several different types of information to be stored in the same physical space at different times. For a union variable, storage is allocated only for the largest of the data types which may reside in the variable.

Structures are a valuable tool for developing complex programs and data structures in an efficient and top down manner.



Previous: 12.5 Common Errors
Up: 12 Structures and Unions
Next: 12.7 Exercises
Previous Page: 12.5 Common Errors
Next Page: 12.7 Exercises

tep@wiliki.eng.hawaii.edu
Sat Sep 3 07:12:43 HST 1994