[c++] "std::endl" vs "\n"

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?

This question is related to c++ coding-style iostream c++-faq

The answer is


The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << '\n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \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)).


They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.


I've always had a habit of just using std::endl because it is easy for me to see.


They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.


There might be performance issues, std::endl forces a flush of the output stream.


If you intend to run your program on anything else than your own laptop, never ever use the endl statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use of endl is know to kill networked file systems like NFS.


There might be performance issues, std::endl forces a flush of the output stream.


Not a big deal, but endl won't work in boost::lambda.

(cout<<_1<<endl)(3); //error

(cout<<_1<<"\n")(3); //OK , prints 3

The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << '\n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \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)).


I recalled reading about this in the standard, so here goes:

See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.

ISO/IEC 9899:201x

7.21.3 §7

At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

7.21.3 §3

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

This means that std::cout and std::cin are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.

However, if std::cout.sync_with_stdio(false) is called, then '\n' will not cause a flush even to interactive devices. Otherwise '\n' is equivalent to std::endl unless piping to files: c++ ref on std::endl.


The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << '\n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \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)).


With reference This is an output-only I/O manipulator.

std::endl Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().

When to use:

This manipulator may be used to produce a line of output immediately,

e.g.

when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly.

Also

An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O. In most other usual interactive I/O scenarios, std::endl is redundant when used with std::cout because any input from std::cin, output to std::cerr, or program termination forces a call to std::cout.flush(). Use of std::endl in place of '\n', encouraged by some sources, may significantly degrade output performance.


They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.


If you intend to run your program on anything else than your own laptop, never ever use the endl statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use of endl is know to kill networked file systems like NFS.


I recalled reading about this in the standard, so here goes:

See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.

ISO/IEC 9899:201x

7.21.3 §7

At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

7.21.3 §3

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

This means that std::cout and std::cin are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.

However, if std::cout.sync_with_stdio(false) is called, then '\n' will not cause a flush even to interactive devices. Otherwise '\n' is equivalent to std::endl unless piping to files: c++ ref on std::endl.


I've always had a habit of just using std::endl because it is easy for me to see.


The std::endl manipulator is equivalent to '\n'. But std::endl always flushes the stream.

std::cout << "Test line" << std::endl; // with flush
std::cout << "Test line\n"; // no flush

The std::endl manipulator is equivalent to '\n'. But std::endl always flushes the stream.

std::cout << "Test line" << std::endl; // with flush
std::cout << "Test line\n"; // no flush

There might be performance issues, std::endl forces a flush of the output stream.


There's another function call implied in there if you're going to use std::endl

a) std::cout << "Hello\n";
b) std::cout << "Hello" << std::endl;

a) calls operator << once.
b) calls operator << twice.


I've always had a habit of just using std::endl because it is easy for me to see.


There's another function call implied in there if you're going to use std::endl

a) std::cout << "Hello\n";
b) std::cout << "Hello" << std::endl;

a) calls operator << once.
b) calls operator << twice.


Not a big deal, but endl won't work in boost::lambda.

(cout<<_1<<endl)(3); //error

(cout<<_1<<"\n")(3); //OK , prints 3

If you use Qt and endl, you could accidentally end up using an incorrect endl which gives you very surprising results. See the following code snippet:

#include <iostream>
#include <QtCore/QtCore> 
#include <QtGui/QtGui>

// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
    QApplication qapp(argc,argv);
    QMainWindow mw;
    mw.show();
    std::cout << "Finished Execution!" << endl;
    // This prints something similar to: "Finished Execution!67006AB4"
    return qapp.exec();
}

Note that I wrote endl instead of std::endl (which would have been correct) and apparently there is a endl function defined in qtextstream.h (which is part of QtCore).

Using "\n" instead of endl completely sidesteps any potential namespace issues. This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.


They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.


There might be performance issues, std::endl forces a flush of the output stream.


With reference This is an output-only I/O manipulator.

std::endl Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().

When to use:

This manipulator may be used to produce a line of output immediately,

e.g.

when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly.

Also

An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O. In most other usual interactive I/O scenarios, std::endl is redundant when used with std::cout because any input from std::cin, output to std::cerr, or program termination forces a call to std::cout.flush(). Use of std::endl in place of '\n', encouraged by some sources, may significantly degrade output performance.


The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << '\n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \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)).


I've always had a habit of just using std::endl because it is easy for me to see.


If you use Qt and endl, you could accidentally end up using an incorrect endl which gives you very surprising results. See the following code snippet:

#include <iostream>
#include <QtCore/QtCore> 
#include <QtGui/QtGui>

// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
    QApplication qapp(argc,argv);
    QMainWindow mw;
    mw.show();
    std::cout << "Finished Execution!" << endl;
    // This prints something similar to: "Finished Execution!67006AB4"
    return qapp.exec();
}

Note that I wrote endl instead of std::endl (which would have been correct) and apparently there is a endl function defined in qtextstream.h (which is part of QtCore).

Using "\n" instead of endl completely sidesteps any potential namespace issues. This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to coding-style

Method Call Chaining; returning a pointer vs a reference? 80-characters / right margin line in Sublime Text 3 Cannot find reference 'xxx' in __init__.py - Python / Pycharm How to stick <footer> element at the bottom of the page (HTML5 and CSS3)? Simple way to create matrix of random numbers Is calling destructor manually always a sign of bad design? Count all values in a matrix greater than a value Iterate through a C++ Vector using a 'for' loop Which comment style should I use in batch files? Dictionaries and default values

Examples related to iostream

'cout' was not declared in this scope How to read line by line or a whole text file at once? How to print Unicode character in C++? Why std::cout instead of simply cout? operator << must take exactly one argument How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT? Why is reading lines from stdin much slower in C++ than Python? How to print (using cout) a number in binary form? Why would we call cin.clear() and cin.ignore() after reading input? Reading a file character by character in C

Examples related to c++-faq

What are the new features in C++17? Why should I use a pointer rather than the object itself? Why is enum class preferred over plain enum? gcc/g++: "No such file or directory" What is an undefined reference/unresolved external symbol error and how do I fix it? When is std::weak_ptr useful? What XML parser should I use in C++? What is a lambda expression in C++11? Why should C++ programmers minimize use of 'new'? Iterator invalidation rules