Difference Between \n and endl


You may have noticed while using cout (console-output) in C++, we have 2 common options to move the cursor to the newline(ie \n and endl). Both \n and endl are used to move the cursor to the next line, but they are not the same in terms of performance and behavior.
#include <iostream>
using namespace std;
int main() {
// Using \n
cout << "Hello with \\n" << '\n';
// Using endl
cout << "Hello with endl" << endl;
return 0;
}
Prerequisites
Concept of Buffer
In most programming languages, output is not sent directly to the screen but first stored in a buffer (a temporary memory area). This buffering improves performance because writing to the screen or an output device is much slower than writing to memory.
Concept of Flushing
Flushing ensures that the output is displayed immediately by forcing the program to send the buffered content to the output device right away. This is useful in situations where real-time updates are required, such as showing progress indicators.
Working
Working of \n
\n
is simply a newline character.When used in the output stream, it moves the cursor to the next line but does not flush the buffer.
The text remains in the output buffer and will only be displayed when:
The buffer is full,
The program ends, or
A flush operation occurs manually/implicitly.
Since it avoids unnecessary flushing,
\n
is faster and preferred in competitive programming and performance-critical tasks
Working of endl
endl
also inserts a newline character, just like\n
.But in addition, it forces the output buffer to flush immediately, sending all buffered content to the output device.
This ensures the output appears instantly, which is useful for debugging, logging, or real-time updates.
However, frequent flushing makes it slower compared to
\n
.
TLDR
Use \n
for speed, use endl
when you need output immediately.
Subscribe to my newsletter
Read articles from Divyansh Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Divyansh Sharma
Divyansh Sharma
I am a Full-Stack Developer specializing in the MERN stack and modern web technologies, with a strong focus on backend development and building clean, functional applications that deliver smooth user experiences. Alongside web development, I enjoy working on Linux development, creating desktop applications, and exploring system administration. Currently, I am expanding my skills in AI integration and cloud technologies to design and implement scalable, future-ready solutions.