Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I don\'t have a specific context in which I\'m asking the question, but while I

ID: 654262 • Letter: I

Question

I don't have a specific context in which I'm asking the question, but while I was reading a beginner book on C++ I noticed the use of both an endl stream manipulator and a newline escape character when dealing with a stream object.

The exmaple is as follows:

cout << "Hello World" << endl;
cout << "Hello World ";
My questions are:

Is it more appropriate to use the stream manipulator (endl) in a certain situation and an escape character in a different one?
Are there drawbacks efficiency wise to using one of the two?
Are they completely interchangeable?
I read that an escape sequence is stored in memory as a single character. Does that mean it is more appropriate to use endl if you're going for low memory consumption?
Does the stream manipulator endl use up memory in any way, if so is it more than the escape sequence?
Thanks, StackExchange Apologies if I posted this in the wrong section, I thought it counted as data structures.

Explanation / Answer

o << endl is equivalent to the following code:

o.put(o.widen(' '));
o.flush();
In other words, you should only use o << endl when you need to flush the stream. For example:

You're about to perform a time-consuming operating and want to make sure you display a message before doing so.
Another process is waiting on your output.
If more than one thread or process is running, you may need to flush output so that the output from each thread or process is displayed correctly. (Otherwise, you may get seemingly random blocks of output interleaved at awkward intervals.)
If you don't need to flush the stream, then use << ' ' instead of endl. The extra calls to flush can hurt performance (sometimes significantly).

For more details, see cppreference.com.

Regarding memory usage: Worrying about versus endl is almost certainly an unnecessary micro-optimization, but in general, I'd expect to take less memory. is just one more byte at the end of a string literal, while writing endl is translated by the compiler into (probably inlined) function calls to put and flush.

Platform-specific differences in line endings (Windows versus Linux and OS X ) are handled at a lower level than endl and o << ' ':

If a stream is opened in text mode, then if you write , it automatically translates it to the appropriate platform-specific line ending. If you read a platform-specific line ending, the stream automatically translates it to .
If a stream is opened in binary mode, then they pass any line endings through verbatim, and it's up to you.
For cout and cin in particular, they're treated as if they're text mode.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote