Difference between ‘endl’ and ‘\n’ in C++

In this tutorial, We are going to learn about endl and \n commands using C++. However, Both the commands are used for the same purpose i.e. To insert a new line. There is a subtle difference between both of them. First, let us see both of their syntaxes to better understand both of the commands.

cout << "Hello World!" << endl;
cout << "Hello World!\n";

The most important difference between them is that, In the endl command, there is an insertion of a new line and flushing of the stream whereas, in \n command, It only inserts a new line.

‘endl’ and ‘\n’ in C++

#include <bits/stdc++.h>

using namespace std;
int main(){
cout<<" hello "<<endl; // it will give new line and flushes the stream
cout << "student";
cout<<"\n"; // it will just give you a new line 
cout<<" to new world ";

return 0;

}

OUTPUT

hello 
student
to new world

Leave a Reply

Your email address will not be published.