Avoid using comparison operators on time_t

As specific in http://www.cplusplus.com/reference/ctime/time_t/, the time_t may be implemented using alternative time representations by libraries.

Just because time_t is arithmetic, that doesn't mean it stores time as monotone increasing values for advancing time. It can be different in different systems.

Although most of linux distros do store it as integer but it is no harm to be careful.
The time.h header file provides us difftime function just for calculating the different by seconds between two time_t variables. Some may worry about the overhead of the function over a simple subtract expression. Well, in some architectures, it's implemented as a macro. For example, POSIX, http://man7.org/linux/man-pages/man3/difftime.3.html

So, the right way to compare 2 time_t values, a, b should be:
if (difftime(b, a) > 0) //...

If you check for a time duration is passed or not, do something like,
time_t now = time(NULL);
if (difftime(now, a) >= duration) //...
As much as you can, avoid using +/- operators on time_t variables for the portability purpose.

Comments