0

According to the definition of endl, it is used to insert a new-line character and flush the stream. And I remember that if a new line is inserted, then the buffer will be flushed automatically. If so, why do endl still need to flushes the stream after inserting a new line.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
o o
  • 145
  • 6
  • 1
    It's the same basic reason why water is wet: the C++ standard says so. – Sam Varshavchik Jul 25 '21 at 17:00
  • o o, "if a new line is inserted, then the buffer will be flushed automatically" --> common. Are you sure it is C++ specified? – chux - Reinstate Monica Jul 25 '21 at 17:02
  • @chux - Reinstate Monica I think so because c does – o o Jul 25 '21 at 17:06
  • You will find a common trick when you don't want to spend the time flushing a stream is to output a newline rather than employing `endl`. It's a common trick because most of the time it works. It's usually only data sent to the user's terminal that's auto-flushed on newline, and that's a decision made by the implementation. – user4581301 Jul 25 '21 at 17:06
  • @oo "because c does" --> It is certainly not specified in C. – chux - Reinstate Monica Jul 25 '21 at 17:07
  • C quite notoriously doesn't have `endl`, so the comparison is a bit weak. – user4581301 Jul 25 '21 at 17:07
  • 2
    You'll probably find [this](https://stackoverflow.com/questions/213907/stdendl-vs-n), and [this](https://stackoverflow.com/questions/30967642/how-can-i-print-a-newline-without-flushing-the-buffer) interesting reads. – WhozCraig Jul 25 '21 at 17:07
  • If you're writing to the terminal it is common practice to just append a line feed. For example `std::cout << "Hello World\n";`. Or `std::cout << "Hello " << variable << '\n';`. – WBuck Jul 25 '21 at 17:16
  • *" if a new line is inserted, then the buffer will be flushed automatically"* - I don't believe this is true. I have no idea why an implementation would make a special case for `\n`. – Galik Jul 25 '21 at 17:39

1 Answers1

8

if a new line is inserted, then the buffer will be flushed automatically

Not necessarily, and not for all streams. It's common for std::cout (and the standard output stream it sends data to) to be line-buffered, but not universal. Some implementations, for example, only line-buffer stdout if output is going to a terminal, and fully-buffer it otherwise (if output is redirected to a pipe, for example).

And that's just for standard output. Other streams like file I/O are almost always fully-buffered and the buffer will only be flushed when it either fills up or its flushed explicitly.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • And, to be clear, flushing the output buffer is rarely useful, and often a performance killer. For console output it doesn't make much difference, but for file I/O, don't mess with buffering unless you know what you're doing. – Pete Becker Jul 25 '21 at 18:39