I'm currently writing a C function that return a time_t value but I need to manage error cases (because this function uses I/O functions) too. Is it correct to use (time_t) -1 as an error indicator?
A way to return error with time_t function in C
1.9k Views Asked by Guid AtThere are 4 best solutions below

Yes, time_t
is signed.
So it perfectly ok to make the function return -1
to indicate an error.
Anyway, you should make sure, that from the logic of your API you never need to return any negative time differences, as time_t
is signed
to be able to express (also?) differences.
Update:
This is guaranteed on POSIX systems only. An even there signed
is in misleading, as http://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/types.h.html defines time_t
to be an int
or a real-floating type.
So on POSIX conforming systems time_t
is able to carry negative values.

The time function itself returns (time_t) -1
on error, so using (time_t) -1
should work just fine.

The value (time_t)-1
indicates 1969-12-31T23:59:59+00:00, the second before The (Unix) Epoch.
It is returned by some of the Standard C time functions, which is a confounded nuisance if you might need to work with historical times and need to distinguish between an actual error and the occasional occurrence of the second before The Epoch. You'd do better with the (hypothetical) TIME_T_MAX or TIME_T_MIN values — the maximum or minimum possible value of time_t
. (But be aware that there's only 25 years or so left before the upper limit for a signed 32-bit time_t
occurs — in January 2038.)
Using
(time_t)-1
is already used bytime()
function to report a failure so does not seem an unreasonable choice:However, if it is necessary for the caller to differentiate between a time related failure or an IO related failure (or specific IO failures) you may consider adding a status type argument to your function that can be used to return additional information about the failure.