1
Copyright © 2010 Dorling Kindersley (India) Pvt. Ltd.
Programming in C—A Practical Approach Structures, Unions, Enumerations and Bit-fields
Introduction • Arrays are used for the storage of homogeneous data. • Hence we have user defined data types like structures, unions, and enumerations to store data with different types. • One of the similarities between arrays and structures is that both of them contain a finite number of elements. Thus, array types and structure types are collectively known as aggregate types. • Unions are similar to structures in all aspects except the manner in which their constituent elements are stored. • In structures, separate memory is allocated to each element, while in unions all the elements share the same memory. • Enumerations help you in defining a data type whose objects can take a limited set of values.
2 Copyright © 2010 Dorling Kindersley (India) Pvt. Ltd.
Programming in C—A Practical Approach Structures, Unions, Enumerations and Bit-fields
Structures A structure is a collection of variables under a single name and provides a convenient way of grouping several pieces of related information together. It can be used for the storage of heterogeneous data. Three important tasks of working with structures: • Defining a structure type i.e. creating a new type. • Declaring variables and constants (i.e. objects) of the newly created type. • Using and performing operations on the objects of the structure type.
3
Copyright © 2010 Dorling Kindersley (India) Pvt. Ltd.
Programming in C—A Practical Approach Structures, Unions, Enumerations and Bit-fields
Defining a Structure The general form of structure type definition is: [storage_class_specifier][type_qualifier] struct [structure_tag_name] { type member_name1[, member_name11, …]; [type member_name2[, member_name22, …]]; ……… } [variable_name];
4
Copyright © 2010 Dorling Kindersley (India) Pvt. Ltd.