Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

endl
c++
flush
stream

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

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring