Ammar Mujtaba Tariq
Ammar Mujtaba Tariq

Reputation: 43

how endl mainly affects fully buffered streams?

https://www.cplusplus.com/doc/tutorial/basic_io/

In the following site, just before cin heading, it is stated that

The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an additional behavior: the stream's buffer (if any) is flushed, which means that the output is requested to be physically written to the device, if it wasn't already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream.

My questions are, why endl mainly affects the fully buffered streams, and how cout is not a fully buffered stream?

Upvotes: 1

Views: 117

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30569

There are three main buffering strategies used for output streams:

  1. No buffering - Every write to the stream is immediately written to the underlying output device.
  2. Line buffering - Writes to the stream are stored in memory until a newline character is written or the buffer is full, at which point the buffer is flushed to the underlying output device.
  3. Full buffering - Writes to the stream are stored in memory until the stream's internal buffer is full, at which point the buffer is flushed to the underlying output device.

why endl mainly affects the fully buffered streams

This should be fairly apparent from the descriptions above. If the stream is unbuffered then std::endl doesn't do any extra work; there is no buffer to flush. If the stream is line buffered, then writing a newline will flush the buffer anyway, so std::endl doesn't do anything extra. Only for a fully buffered stream does std::endl do any extra work.


how cout is not a fully buffered stream?

The C++ language doesn't specify the buffering strategy used for std::cout, but most implementations use either no buffering or line buffering when the program's standard output stream is hooked up to a terminal. If stdout is redirected to something else, like a file, many implementations will switch to using a fully buffered stream for std::cout.

Upvotes: 4

Related Questions