When printing text with std::cout, we often want to end the line.
C++ gives us more than one way to do that, but they are not identical. \\n inserts a newline. std::endl inserts a newline and flushes the stream
The usual case: print a newline
Most of the time, this is all you need:
#include <iostream>
int main(){
std::cout << "Hello, C++\n";
std::cout << "This is the next line.\n";
}
The \\n character moves the output to a new line.
It can be embedded directly inside a string literal. You can’t do this with std::endl.
std::cout << "And that's all, folks!\n";
This is concise and clear. There is no visual clutter.
What std::endl actually does
std::endl does two things:
- Inserts a newline character.
- Flushes the output stream.
Flushing means forcing buffered output to be written immediately.
In simplified terms, this:
std::cout << "Hello" << std::endl;
behaves like this:
std::cout << "Hello\\n";
std::cout.flush();
Flushing the buffer repeatedly is wasteful, inefficient and unnecessary.
Additionally, C++’s output system is designed to self-flush periodically, and it’s both simpler and more efficient to let it flush itself.
Takeaway
Use \\n for normal line breaks.
Use std::endl only when you intentionally need to flush.