A question/curiosity: When using the time function, why must the argument be 0, as "time(0)"? I tried other numbers and it gave error.

Recommended Answers

All 7 Replies

time's parameter is an alternate return path. If you pass in NULL (or 0) it is ignored. Otherwise, you must pass the address of a time_t object which will be filled with the time.

commented: Good clear answer! +8

time(0); or time(NULL); returns the system time in seconds ...

The C++ Declaration of the 'time()'-function looks as follows: time_t time ( time_t * timer ); So if you pass a NULL-pointer as argument, it will just return the time ...
But between the brackets you can also type the name of a 'time_t' object and call the function with a 'time_t'-object as parameter ...
When doing this the function saves the system time (in seconds) to the 'time_t'-object ...

Hope this helps !

Source: http://www.cplusplus.com/reference/clibrary/ctime/time.html

Wow, Sorry, I didn't read the thread carefully ...
I just see that nucleon did already explain why ...

The more the merrier!
I wonder why it has that parameter, though.
Seems kind of pointless.

Thanks for the explanations, everyone!

time(0); or time(NULL); returns the system time in seconds ...

The C++ Declaration of the 'time()'-function looks as follows: time_t time ( time_t * timer ); So if you pass a NULL-pointer as argument, it will just return the time ...
But between the brackets you can also type the name of a 'time_t' object and call the function with a 'time_t'-object as parameter ...
When doing this the function saves the system time (in seconds) to the 'time_t'-object ...
Source: http://www.cplusplus.com/reference/clibrary/ctime/time.html

Alas, the time() function does NOT return the system time in seconds. Regrettably, so an authoritative source as cplusplus.com presents an incorrect example of the time function usage.
The C language (7.23.1):

The range and precision of times representable in clock_t and time_t are implementation-defined.

So the size_t is an arithmetic type capable of representing times - that's all.
However the double difftime(time_t t1, time_t t0) function returns the difference t1-t0 expressed in seconds as a double.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.