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??
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
orctime
.
http://en.cppreference.com/w/cpp/chrono/c/ctime
The string may be shared between
std::asctime
andstd::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.
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