Ian said:
When adding two values of type time_t, how can I check for overflow?
Maybe I'm just brain-cramped today, but I can't figure out how to do it.
Arithmetic on two time_t variables or adding other values to a time_t
is not the intent of Standard C. The Standard does not specify
the exact type or what its instrumentality. The Standard only states
it to be an arithmetic type capable of representing time. One would
need to consult the implementation documation to manipulate the
time_t variables as you mention. The resulting code would not
be portable. Standard C conceals having to do this by providing
shrouds in functions to manipulate time (eg. functions localtime,
mktime) and to determine the difference in time (function difftime).
For example, below is an attempt to add 10 secs to a time with
the += operator (tp->tm_sec += 10
. It would rarely be neccessary
for the need to check for overflow,underflow but you are
able to do so because tp->tm_sec is defined by the Standard to be a
type int.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void ExitTimeFailure(void);
int main(void)
{
struct tm *tp;
time_t now, then;
if((now = time(NULL)) == (time_t)-1) ExitTimeFailure();
tp = localtime(&now);
tp->tm_sec += 10; /* Add 10 sec */
if((then = mktime(tp)) == (time_t)-1) ExitTimeFailure();
printf("The difference in time between then and now"
" is %.1f seconds\n", difftime(then, now));
return EXIT_SUCCESS;
}
void ExitTimeFailure(void)
{
puts("Unable to determine a time");
exit(EXIT_FAILURE);
}