tags:

views:

124

answers:

5

Real simple question. According to my man-page, these two will do the same:

time_t t;
time(&t);

printf("Time: %ld", t);

...

printf("Time: %ld", time(NULL));

So, what exactly is the benefit of passing a pointer to time? In case time() would fail due to no clock being available, neither of the two variants will have any benefit in my opinion.

A: 

From the man-page:

time_t time(time_t *t);

"If t is non-NULL, the return value will also be stored in the memory pointed to by t."

I guess it's just legacy stuff.

Maister
The OP gets this. He's asking _why_ you would want to pass a non-NULL pointer.
Marcelo Cantos
+1  A: 

Most examples I've seen pass NULL. I likewise see no benefit in passing a meaningful pointer, especially since time_t is pretty much always just an integral type.

Marcelo Cantos
A: 

I believe if you want to save the value of the time you call time like this:

time_t current = time(NULL);

However, time_t itself is generally just an integer value.

wheaties
+6  A: 

The benefit would be that you do not have to copy the data into another structure after calling 'time'.

If you are e.g. preparing a buffer of data to send to another application/server you would have to copy the data, which is additional overhead. By passing a pointer into your data structure you could put it right in the correct place in one shot.

Of course if your only use for the data is to convert it to another format such as a text printf, then it is more efficient to call it with NULL and save the additional storage required by your first example.

Lastly since the time function uses a single location for storage of it's internal time structure the first method would be more thread-safe, although I cannot remember of the top of my head if 'time' is in fact thread safe.

Cobusve
A: 

Pointer to time_t value passed as a function argument -- IMO that is one reason why the syntax exists.

time_t *foo(time_t *dest)
{
     time(dest);
     /* do something with dest here */
     return dest;
}
jim mcnamara