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?
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
The difference can be illustrated by the following:
std::cout << std::endl;
is equivalent to
std::cout << '\n' << std::flush;
std::endlIf you want to force an immediate flush to the output.
\nif you are worried about performance (which is probably not the case if you are using the
\n on most lines.
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::cout being special but still files (or file-like)).