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

'\n' writes a new line character. std::endl writes it and also flushes the output buffer (forces the text to go out at once). The flush is slow when you print many lines.

#include <chrono>
#include <iostream>
#include <sstream>

int main() {
    std::ostringstream a, b;
    for (int i = 0; i < 3; i++) a << i << '\n';
    for (int i = 0; i < 3; i++) b << i << std::endl;
    std::cout << (a.str() == b.str()) << '\n';       // the same text
}
Output

1

Use '\n' in normal code. Use std::endl only when you really need the flush, for example before a crash log.


Learn more about the similar topics:
Tutorials
C++ Introduction
C++ History and Versions
C++ Features
C++ vs C
C++ Installation and Setup
Your First C++ Program: Hello World
C++ Syntax
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is C++?
What are the main features of C++?
What is the difference between C and C++?
What are the different versions (standards) of C++?
What is the use of #include in C++?
What is the difference between cout and printf in C++?
What is the difference between endl and \n in C++?