Programming in C

(Barry) #1

180 Chapter 9 Working with Structures


After the time has been entered, the program calls the timeUpdatefunction, passing
along the currentTimeas the argument.The result returned by the function is assigned
to the struct timevariable nextTime, which is then displayed with an appropriate
printfcall.
The timeUpdatefunction begins execution by “bumping” the time in nowby one
second. A test is then made to determine if the number of seconds has reached 60. If it
has, the seconds are reset to 0 and the minutes are increased by 1. Another test is then
made to see if the number of minutes has now reached 60, and if it has, the minutes are
reset to 0 and the hour is increased by 1. Finally, if the two preceding conditions are sat-
isfied, a test is then made to see if the hour is equal to 24; that is, if it is precisely
midnight. If it is, the hour is reset to 0.The function then returns the value of now,
which contains the updated time, back to the calling routine.

Initializing Structures


Initializing structures is similar to initializing arrays—the elements are simply listed inside
a pair of braces, with each element separated by a comma.
To initialize the datestructure variable todayto July 2, 2005, the statement
struct date today = { 7, 2, 2005 };
can be used.The statement
struct time this_time = { 3, 29, 55 };
defines the struct timevariable this_timeand sets its value to 3:29:55 a.m. As with
other variables, if this_timeis a local structure variable, it is initialized each time the
function is entered. If the structure variable is made static (by placing the keyword
staticin front of it), it is only initialized once at the start of program execution. In
either case, the initial values listed inside the curly braces must be constant expressions.
As with the initialization of an array, fewer values might be listed than are contained
in the structure. So the statement
struct time time1 = { 12, 10 };
sets time1.hourto 12 and time1.minutesto 10 but gives no initial value to
time1.seconds. In such a case, its default initial value is undefined.
You can also specify the member names in the initialization list. In that case, the gen-
eral format is
.member = value
This method enables you to initialize the members in any order, or to only initialize
specified members. For example,
struct time time1 = { .hour = 12, .minutes = 10 };
Free download pdf