Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what determines what bytes are output from std::endl

I have a large code base that uses std::cout to generate its output, and it uses std::endl all over the place to generate its newlines. This program seems to generate only linefeeds for the endl, which isn't a huge problem in itself, but for whatever reason, wasn't what I had expected.

So as a reality check, I built a simple program to pump endl's into cout, compiled it with the same compiler and examined the output from that. That program emits both CR and LF for endl.

It doesn't look like the large program plays any games with cout to change the way endl works, at least not that I can recognize, so it seems strange that it should behave differently than the small program. It seems as though the large program must be doing something to change the defaults. What am I missing here?

Both programs were compiled using MinGW gcc 4.5.2 on 32bit windows.

like image 410
JustJeff Avatar asked Jan 19 '23 22:01

JustJeff


1 Answers

To add to Tomalak Geret'kal's answer: the fact that endl expands to the platform-specific endline is a popular misconception.

Inside a C/C++ application the only "official" newline (at least, as far as streams and stream-related functions are concerned) is '\n'. The translation from '\n' to the platform-specific newline is done inside the streams1 when they are opened in text mode (i.e. without the ios::bin flag).

endl, instead, is used to force a stream flush after the '\n'; this can be useful for console output, but (1) often this is not the case (cout is automatically flushed when input is requested from cin via the tied-stream mechanism) and only wastes CPU time, and (2) you often find it used also on file streams, where it is almost never useful, and results in poor file writing performance.


  1. As discussed in the comments, as far as the standard is concerned the translation could actually happen at any level below the stream (e.g. the stream may translate the presence/absence of ios::bin into a flag for the underlying OS file management functions, and it would be responsibility of the OS to do the translation); in reality, mainstream OSes do not have particular flags for this kind of translation, mainly because their file APIs are content-agnostic (you tell them what to write, they write it without modifications).
like image 87
Matteo Italia Avatar answered Jan 28 '23 11:01

Matteo Italia