Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird C++ Behavior while printing our time on cout

Tags:

c++

Running following code:

  1 #include <iostream>
  2 int main(int argc, char** argv)
  3 {
  4     time_t t1 = time(0);
  5     time_t t(0);
  6     std::cout<<"BUG LINE"<<std::endl<< ctime(&t) << ctime(&t1) ;
  7     std::cout<<"PRINTS FINE HERE"<<std::endl;
  8     std::cout<< ctime(&t);
  9     std::cout<< ctime(&t1);
 10     return 0;
 11 }

Building: g++ test1.cpp

Output:
./a.out
BUG LINE
Thu Jan  1 01:00:00 1970
Thu Jan  1 01:00:00 1970
PRINTS FINE HERE
Thu Jan  1 01:00:00 1970
Wed Jul 10 16:31:48 2013

Why is the stream going weird in the #6 of the code??

like image 833
Saurabh Kumar Avatar asked Dec 21 '22 03:12

Saurabh Kumar


1 Answers

http://www.cplusplus.com/reference/ctime/ctime/

The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime.

http://en.cppreference.com/w/cpp/chrono/c/ctime

The string may be shared between std::asctime and std::ctime, and may be overwritten on each invocation of any of those functions.

In your example, on line 6, ctime(&t1) gets evaluated first, then ctime(&t) which overwrites the string (whichever is evaluated first is unspecified, and compilers often evaluate in reverse order (often, not always)).

TL;DR: Reading the docs may help.

like image 83
gx_ Avatar answered Dec 24 '22 02:12

gx_