Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Program to compute elapsed time, learning structures and functions Date: Thu, 05 Nov 2015 12:42:16 -0800 Organization: None to speak of Lines: 53 Message-ID: References: <96d1b3f5-3ab0-4b14-a0bc-8f7e6e07fa0a@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="3532"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX194cR2YtUjXGoUih8AhpX2O" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:RatQBBMl5h1bRXHw9lRQvFHPmzY= sha1:+jLSjRr4EF8tiauKvQIGgQKXWAw= Xref: csiph.com comp.lang.c:75013 Alla _ writes: > Long time after I created this thread, I have corrected the > program, and it works now. Thank you for your help! > > // Program to computed elapsed time between two times > #include > > struct time > { > int hour; > int minutes; > int seconds; > }; > > struct time elapsed_time (struct time time_1, struct time time_2); [snip] You're doing something to handle wraparound from one day to the next, but I don't think you're doing it consistently. This also interacts oddly with out-of-order input. For example: 1:00:00 3:00:00 --> 02:00:00 3:00:00 1:00:00 --> 22:00:00 49:00:00 00:00:00 --> -25:00:00 00:00:00 49:00:00 --> 49:00:00 You need a consistent definition of how the program should behave in these corner cases -- which includes defining just what you mean by "elapsed time". Restricting the permitted input values (and aborting with an error message when the restrictions are violated) is a reasonable approach if you don't want to handle bizarre inputs. You have a great deal of code in your elapsed_time function that deals with the hour, minutes, and seconds fields separately. An alternative approach (one that I'd probably use) is to convert the "struct time" value to a raw number of seconds, compute the difference, and then convert back to a "struct time" result. Encapsulating the struct time <--> raw seconds conversions into their own functions would IMHO make the code easier to read and understand. There might be some concern for overflow, if 3600*hour + 60*minute + seconds might exceed INT_MAX, but storing raw seconds in a long or even a long long would avoid that for any "reasonable" time intervals. Storing a number of seconds in a "long" covers an interval of at least 68 years. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"