Working with Structures in C: Structure Variants

You do have some flexibility in defining a structure. First, it is valid to declare a variable to be of a particular structure type at the same time that the structure is defined. This is done simply by including the variable name (or names) before the terminating semi- colon of the structure definition. For example, the statement

struct date

{

int month;

int day;

int year;

} todaysDate, purchaseDate;

defines the structure date and also declares the variables todaysDate and purchaseDate to be of this type.You can also assign initial values to the variables in the normal fashion. Thus,

struct date

{

int month;

int day;

int year;

} todaysDate = { 1, 11, 2005 };

defines the structure date and the variable todaysDate with initial values  as indicated.

If all of the variables of a particular structure type are defined when the structure is defined, the structure name can be omitted. So the statement

struct

{

int month;

int day;

int year;

} dates[100];

defines an array called dates to consist of 100 elements. Each element is a structure containing three integer members: month, day, and year. Because you did not supply a name to the structure, the only way to subsequently declare variables of the same type is by explicitly defining the structure again.

You have seen how structures can be used to conveniently reference groups of data under a single label.You’ve  also seen in this chapter how easily you can define arrays of structures and work with them with functions. In the next chapter, you learn how to work with arrays of characters, also known as character strings. Before going on, try the following exercises.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *