endl vs \n in C++ differences & similarities
If you’re new to C++ programming, you’ll seldomly see endl and \n in most examples and programmes. One thing you have to keep in mind is that, they both do the same thing but the way you’ll have to include them in your C++ programme varies a bit.
“endl” inserts a new line and flushes the stream(output buffer), whereas “\n” just inserts a new line.
For instance, consider the following “Hello World” C++ programme:
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello World\n";
std::cout << "Hello World" << endl;
}
Both will print out Hello World followed by a new line to the terminal but as you can see, the \n is wrapped up with double quotes whereas endl isn’t.
Another difference is that, endl doesn’t occupy memory where \n occupies 1 byte memory because it’s a character. Furthermore, endl is only supported in C++ whereas \n is supported both in C and C++.
Lastly, endl keeps flushing the queue in the output buffer throughout the process whereas \n flushes the output buffer only once at the end of the program.