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:
#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.