Many C++ books contain example code like this...
std::cout << "Test line" << std::endl;
...so I've always done that too. But I've seen a lot of code from working developers like this instead:
std::cout << "Test line\n";
Is there a technical reason to prefer one over the other, or is it just a matter of coding style?
What is the difference between endl and \n in C++? Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not.
The difference is obvious. The second one is much faster. std::endl always flush es the stream. In turn, \n simply puts a new line character to the stream, and in most cases this is exactly what we need.
Endl flushes the output buffer and '\n' doesn't. if you want the buffer flushed frequently, use '\n'. if you do, use endl. Endl is actually slower because it forces a flush, which actually unnecessary.
std::endl writes a newline to the output stream and flushes it. In most cases, the developer doesn't need to flush. Flushing operation is expensive, because it involves a system call.
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl
flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.
The difference can be illustrated by the following:
std::cout << std::endl;
is equivalent to
std::cout << '\n' << std::flush;
So,
std::endl
If you want to force an immediate flush to the output.\n
if you are worried about performance (which is probably not the case if you are using the <<
operator).I use \n
on most lines.
Then use std::endl
at the end of a paragraph (but that is just a habit and not usually necessary).
Contrary to other claims, the \n
character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin
and std::cout
being special but still files (or file-like)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With