C++ 如果返回-1,是否修改time()的参数?
更新: 是:C++ 如果返回-1,是否修改time()的参数?,c++,C++,更新: 是:time()的参数和返回值在出错时均为-1。我在中添加了GNU代码 原始问题: time()函数声明为:std::time\u t time(std::time\u t*arg) 如果time()返回-1,是否更新arg time_t arg = 42; time_t result = time(&arg); cout << "arg: " << arg << ", result: " <&l
time()
的参数和返回值在出错时均为-1
。我在中添加了GNU代码
原始问题:
time()
函数声明为:std::time\u t time(std::time\u t*arg)代码>
如果time()
返回-1
,是否更新arg
time_t arg = 42;
time_t result = time(&arg);
cout << "arg: " << arg << ", result: " << result << endl;
C11标准(C++标准引用C库函数),在7.27.2.4/3中表示:
time
函数返回实现与当前时间的最佳近似值
日历时间。如果未指定日历时间,则返回值(时间)(-1)
可用如果timer
不是空指针,则返回值也会分配给它所指向的对象。
因此,在您的代码中,arg
的值将始终被写入,您不需要初始化它
请注意,最好完全忽略它,然后编写time\t result=time(NULL)代码> 参数在出错时将返回-1
GNU的定义如下:
/* Return the current time as a `time_t' and also put it in *T if T is
not NULL. Time is represented as seconds from Jan 1 00:00:00 1970. */
time_t
time (time_t *t)
{
struct timeval tv;
time_t result;
if (__gettimeofday (&tv, (struct timezone *) NULL))
result = (time_t) -1;
else
result = (time_t) tv.tv_sec;
if (t != NULL)
*t = result;
return result;
}
事实上,你花了这么多的心思在它上面,这表明下一个读到这篇文章的程序员可能会有同样的问题,所以你不妨初始化它。它基本上不需要任何成本。使用std::chrono::其中一个时钟::now()
来颠覆整个问题?我的编译器抱怨time\t arg代码>未首先初始化就已开始使用。我可以使用time\u t arg=-1代码>但如果在下一行设置该值,则这似乎毫无意义。最后,我只是想确定arg
在time()返回-1
时是否会保持不变(如果返回错误值,某些函数会保持参数不变)。
/* Return the current time as a `time_t' and also put it in *T if T is
not NULL. Time is represented as seconds from Jan 1 00:00:00 1970. */
time_t
time (time_t *t)
{
struct timeval tv;
time_t result;
if (__gettimeofday (&tv, (struct timezone *) NULL))
result = (time_t) -1;
else
result = (time_t) tv.tv_sec;
if (t != NULL)
*t = result;
return result;
}