I have a time_t type variable (from <time.h>
) that stores the time of a failure, and would like to initialize it to a "null" value that will be the final value if no error occurs. Is there a standard way to set a time_t variable to some kind of known null value? I see that the time()
function returns -1 if an error occurs, maybe this is best, but wonder if I can just assign an integer value to a typedef like that. Maybe I'd need to use this...?
time_t failTime = (time_t)(-1);
As OP referred, the result from a failed time()
(and other standard C library functions) is (time_t)(-1)
, so it is at least reasonable to initialize time_t
to that "fail" value.
// Just like OP
time_t failTime = (time_t)(-1);
time_t
is a real type and "integer and real floating types are collectively called real types" . time_t
could be a double
, long
, etc.
Strictly speaking time_t
could encode a valid time as (time_t)(-1)
, yet that is not distinguishable from an error return for various functions.
Given the wide latitude of possible encoding and considering common practice to use integer seconds since Jan 1, 1970, (time_t)(-1)
is a reasonable choice.
A more robust (or pedantic solution) would pair a flag with the time variable to indicate its correctness. Example:
struct time_pedantic {
time_t t;
bool valid;
}