计算可由time_t数据类型表示的最近时间。如果超出了这一时间将会如何?
C++11标准规定long类型最少占32位,在我的计算机上,系统使用long int来实现time_t,实际使用64位来表示long类型,因此其取值值范围为 -9223372036854775808~9223372036854775807,由于该值特别大,2900亿年后才会溢出,此时宇宙可能都不存在了。对于某些32位系统或者旧的程序,它们的time_t类型是使用32位int来实现的,而int取值范围为-2147483648~2147483647,我们可以利用localtime( )函数来分解该值,并用strftime( )函数来打印,程序如下:
#include <iostream>
#include <climits>
#include <ctime>
int main (int argc, char *argv[])
{
time_t tm_t = INT_MAX;
tm* tmp = nullptr;
char buf[64] = {0};
if (tmp = localtime(&tm_t))
{
strftime(buf, 63, "%Y/%m/%e %H:%M:%S \n", tmp);
}
std::cout << buf << std::endl;
return 0;
}
程序运行结果如下:
image.png
由于我的本地北京时间有8个小时的时差提前,因此真正的溢出时间为2038年1月19日03:14:07。如果到这一天将会溢出,由于int是有符号数,而C和C++标准都对有符号数溢出行为未定义,因此程序的行为无法预计,可能崩溃,可能复位,可能溢出后是个无法估计的值。