Search code examples
cunixtimeunsignedtimeval

Is there a benefit in using unsigned long for timeval members?


I noticed some programmers use unsigned long for tv_sec and tv_usec [when they copy them or operate with them] of timeval while they are defined as simply long.

Though it does make me wonder why they were defined like that when time usually goes forward.


Solution

  • Using long int for those variables will work until year 2038, and after that the tv_sec will overflow on machines where long is 4bytes.

    timeval shall be defined as:

    The <sys/time.h> header shall define the timeval structure that includes at least the following members:
    
    time_t         tv_sec      Seconds. 
    suseconds_t    tv_usec     Microseconds. 
    

    You should notice that time_t type is used instead of long, but which is also a 32bit representation on some systems while there are even 64bit representations on other systems. In order to avoid overflow, time_t will probably be changed to an unsigned 32bit integer or a 64bit one.

    That is why some are using unsigned long, as it will stop the overflow until year 2100+. You should use the time_t type instead, and you won't need to think about how long your program is supposed to run for in the future.