Question

I have noticed strange behaviour when printing output to a stream. My code loops through a large dataset and, amongst other things, reads a timestamp from each item. The timestamp from the first item is stored so an elapsed time can be calculated.

CurTime = ev[i].MidasTimeStamp;
RunTimeElapsed = difftime(CurTime,StartTime);
cout << "StartTime: " << ctime(&StartTime) << "CurTime: " << ctime(&CurTime) << "Elapsed: " << RunTimeElapsed << " s" << endl;  

The output printed to screen shows the same time printed twice e.g:

StartTime: Mon Sep 23 14:44:57 2013
CurTime: Mon Sep 23 14:44:57 2013
Elapsed: 360 s

But if split the print line into two:

cout << "StartTime: " << ctime(&StartTime); 
cout << "CurTime: " << ctime(&CurTime) << "Elapsed: " << RunTimeElapsed << " s" << endl; 

I get the expected output:

StartTime: Mon Sep 23 14:44:57 2013
CurTime: Mon Sep 23 14:50:57 2013
Elapsed: 360 s

The only change between the two outputs was to the cout line(s). This is easy enough to work around but I'd like to understand what's happening.

Was it helpful?

Solution

From the documentation on ctime:

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

The order of evaluation of subexpressions within the expression is unspecified. In particular, it is legal for the compiler to call ctime twice first, then call operator<< as necessary. This is what seems to happen in your case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top