Programming in C

(Barry) #1
Initializing Structures 181

sets the time1variable to the same initial values as shown in the previous example.The
statement


struct date today = { .year = 2004 };


sets just the year member of the date structure variable todayto 2004.


Compound Literals


You can assign one or more values to a structure in a single statement using what is
know as compound literals.For example, assuming that todayhas been previously declared
as a struct datevariable, the assignment of the members of todayas shown in
Program 9.1 can also be done in a single statement as follows:


today = (struct date) { 9, 25, 2004 };


Note that this statement can appear anywhere in the program; it is not a declaration
statement.The type cast operator is used to tell the compiler the type of the expression,
which in this case is struct date, and is followed by the list of values that are to be
assigned to the members of the structure, in order.These values are listed in the same
way as if you were initializing a structure variable.
You can also specify values using the .membernotation like this:


today = (struct date) { .month = 9, .day = 25, .year = 2004 };


The advantage of using this approach is that the arguments can appear in any order.
Without explicitly specifying the member names, they must be supplied in the order in
which they are defined in the structure.
The following example shows the dateUpdatefunction from Program 9.4 rewritten
to take advantage of compound literals:


// Function to calculate tomorrow's date – using compound literals


struct date dateUpdate (struct date today)
{
struct date tomorrow;
int numberOfDays (struct date d);


if ( today.day != numberOfDays (today) )
tomorrow = (struct date) { today.month, today.day + 1, today.year };
else if ( today.month == 12 ) // end of year
tomorrow = (struct date) { 1, 1, today.year + 1 };
else // end of month
tomorrow = (struct date) { today.month + 1, 1, today.year };

return tomorrow;
}

Free download pdf