Search code examples
c++ctime

how to correctly use ctime() to print different time stamps


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

Solution

  • 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.