I was expecting the following code should print different time stamps t1 and t2, however the result shows t1 and t2 are the same. Where did I make the mistake?
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
time_t t1 = time(NULL);
cout << "time now " << ctime(&t1) << endl;
time_t t2 = t1 + 10000.0;
cout << "time now " << ctime(&t1) << endl << " time later " << ctime(&t2) <<endl;
}
Result:
time now Thu Apr 28 20:37:03 2016
time now Thu Apr 28 20:37:03 2016
time later Thu Apr 28 20:37:03 2016
printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, ptm->tm_min, ptm->tm_sec); We use the tm_hour , tm_min , and tm_sec members to express a human-readable time format.
ctime() Function in C/C++ The ctime() function returns the string representing the localtime based on the argument timer. Syntax: char *ctime(const time_t *timer) Parameters: This function accepts single parameter time_ptr. It is used to set time_t object that contains a time value.
The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds.
The answer to your question can be found in the manual page for the ctime() function:
The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions.
ctime() returns a pointer to an internal buffer it uses. Every time it's called, it returns a pointer to the same buffer:
cout << "time now " << ctime(&t1) << endl << " time later " << ctime(&t2) <<endl;
For this line of code, your compiler generated code that calls ctime()
twice, then executes the <<
operator. But on the second call to ctime()
, it overwrote the buffer with the second time, so when the <<
operator formats the output, because the result of the first call to ctime()
is the same pointer, and the buffer that it points to has been overwritten by the second call to ctime()
, you get the same time printed twice.
Thank you for posting a Minimal, Complete, and Verifiable example.
What is ctime
actually returning? From cppreference:
Pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between
std::asctime
andstd::ctime
, and may be overwritten on each invocation of any of those functions.
It likely works out that on your compiler, the later ctime()
gets called first, then the newer ctime()
, then both operator<<()
s get evaluated - which emit the same char*
. As a result of the unspecified order, your code has undefined behavior. On some compilers, it could work as you hoped it would! On yours, it happens not to.
If you separate out the two calls:
cout << "time now " << ctime(&t1) << endl;
cout << " time later " << ctime(&t2) <<endl;
you'd definitely and consistently see different values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With