Difference Between “\n” and “std::endl” in C++.

Shashank Saraswat
2 min readJul 6, 2021

If your are a competitive programmer than you need to know what is the difference between “\n” and “std::endl” in C++. Most of you say both are used for line breaking. you are right but you know “\n” is much faster then std::endl? if you don’t know. let me explain how.

This is because, they might be doing the same task, but under the hood their mechanisms are completely different.
“\n” is just an escape sequence which inserts a new line to the output stream.
But “std::endl” is an object which not only inserts a new line to the stream but also flushes the buffer each time it is used. This means std::endl is equivalent to ‘\n’ followed by an std::flush().
Now some of you might be thinking that what is all this gibberish — flush, buffer etc.?

Let me explain Buffer and Flushes in easy term.

𝗕𝘂𝗳𝗳𝗲𝗿 → is a temporary storage area which holds the output until it is flushed. Example.

for(int i=1; i<=10; i++){
cout << i << std::endl ;
}

Here the output buffer is flushed whenever std::endl is encountered. Therefore, buffer is flushed 10 times.

𝗙𝗹𝘂𝘀𝗵𝗶𝗻𝗴 → is the process of transferring the data in the buffer to the output device.

for(int i=1; i<=10; i++){
cout << i << ‘\n’ ;
}

But using ‘\n’ would fill up the buffer with all the 10 numbers first and then flush it only once at the end of the program.

Flushing of buffers is an Operating System task. Every time the buffer is flushed, a request has to be made to the Operating System and these requests are comparatively expensive. Furthermore, we don’t really need to flush the buffer every time we write something to the stream, since the buffers get flushed automatically when they get full.

While the difference is not obvious in smaller programs, std::endl performs significantly worse than ‘\n’ because of the constant flushing of the output buffer. Therefore, writing ‘\n’ characters directly to the stream is more efficient since it doesn’t force a flush like std::endl.

Connect with me on LinkedIn.

Thanks Sukhseerat Kaur for explaining in such a good way.!

--

--

Shashank Saraswat
0 Followers

Programmer | Developer | Learner | Artist | Computer Science Student