Why the order is not preserved when printing something, first with cerr and then cout?

std::cerr and std::cout are different streams and they are not synchronized. So you really can't assume anything about how output to both gets shown. In this case, the output happens to be shown before the error.

You can rely on the order within either stream.

Additionally, std::cout is buffered and std::cerr is not, and that often causes this kind of problem, but because you are using std::endl (which flushes the stream) this doesn't really apply in your case.


The order of those two lines was not changed. However, whatever code produced the output you saw failed to preserve the order in which the output was sent to the two streams. It's possible that it just waited and then read both streams to produce the final output. It's hard to be sure without knowing what your environment looks like.

Tags:

C++

Std