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;
}