Trusted answers to developer questions

What is the difference between endl and \n in C++?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

Anything that is to be outputted is first queued into an output buffer and then written to the device (hard disk, monitor, etc.), flushing the queue in the process.

Let’s understand this with an example where we will need to print the 26 letters of the English alphabet on the screen:

svg viewer
#include <iostream>
using namespace std;
int main() {
for (char i='A'; i <= 'Z'; i++)
{
cout << i << endl;
}
return 0;
}

Here, the output buffer is flushed every time the code executes line 7. Hence, the buffer is flushed 26 times (once after printing each letter).

Using \n would fill up the output buffer with all 26 characters first and flush it only once at the end of the program:

#include <iostream>
using namespace std;
int main() {
for (char i='A'; i <= 'Z'; i++)
{
cout << i << "\n";
}
return 0;
}

While the difference is not obvious in smaller programs, endl performs significantly worse than \n because of the constant flushing of the output buffer.

RELATED TAGS

endl
c++
flush
stream
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?