Error return method using time_t function in C

I am currently writing a C function that returns time_t, but I need to handle cases of errors (because this function also uses I / O functions). Is it correct to use (time_t) -1 as an error indicator?

+4
source share
4 answers

Using (time_t)-1 , time() already used to report a failure, so the choice doesn't seem unreasonable:

The current calendar time, encoded as a time_t object on success, (time_t) (- 1) on error. If the argument is not NULL, the return value is equal to the value stored in the object that the argument points to.

However, if you want the caller to distinguish between a time-related IO failure or failure (or specific IO failures), you might consider adding a status type argument to your function, which can be used to return additional information about the failure.

+3
source

Yes, time_t signed.

So it's great for a function to return -1 to indicate an error.

In any case, you should make sure that from the logic of your API you never need to return any negative time differences, since time_t is signed to be able to express (also?) The differences.

Update:

This is only guaranteed for POSIX systems. Even there signed is misleading, as http://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/types.h.html defines time_t as an int or a real floating-point type.

Thus, POSIX systems corresponding to time_t systems can carry negative values.

+2
source

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

+2
source

The value (time_t)-1 indicates 1969-12-31T23: 59: 59 + 00: 00, the second before the era (Unix).

It is returned by some of the standard C time functions, which is a confusing nuisance if you may have to work with historical times and need to distinguish between the actual error and the accidental appearance of the second before the era. You would rather make (hypothetical) TIME_T_MAX or TIME_T_MIN values ​​- the maximum or minimum possible time_t value. (But keep in mind that only 25 years are left before the upper limit for the signed 32-bit time_t is in January 2038.)

+1
source

Source: https://habr.com/ru/post/1439420/


All Articles