Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get maximum value for time_t with Visual Studio

I need to get the following code working platform independent:

 timeval tv;
 tv.tv_sec = std::numeric_limits<time_t>::max();

This code works fine under all kinds of Linux OS and Mac OS X.

Unfortunately under windows this would return -1, for tv.tv_sec.

I thought then about redefining time_t like this:

 typedef int time_t;

This did not work either as the comiler complains now about:

error C2371: 'time_t' : redefinition; different basic types

How can I get the code this code running on plattform independent?

like image 272
tune2fs Avatar asked Nov 16 '11 18:11

tune2fs


2 Answers

tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();

Alternative without decltype

template<typename T> 
void set_max(T& val){val = std::numeric_limits<T>::max();}

set_max(tv.tv_sec);
like image 167
ronag Avatar answered Sep 27 '22 23:09

ronag


You can't do this portably. time_t isn't even necessarily an integral type. It could be a struct or anything really.

Since it looks like you're setting the tv_sec member of a struct timeval, why don't you just use the right type there? That's defined as a long int, so you should do:

tv.tv_sec = std::numeric_limits<long int>::max();

Although, I notice now that POSIX says tv_sec is a time_t even though MSDN and the GNU libc use long int. These old time APIs that can't even distinguish between durations and time points are definitely due for replacement. If you can use C++11 check out std::chrono.

Anyway, std::numeric_limits<std::time_t>::max() actually does give the max time_t value, even on Windows. The problem is just that Window's definition for timeval::tv_sec isn't time_t as POSIX mandates, and so the cast to long int gets you the negative number.

However this can be fixed on Windows by defining _USE_32BIT_TIME_T. This will cause the definition for time_t to match the type used in timeval for tv_sec, and then your std::numeric_limits<time_t>::max() will work.

like image 34
bames53 Avatar answered Sep 27 '22 23:09

bames53