Skip to content
Related Articles

Related Articles

endl vs \n in C++

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 09 Jun, 2022

endl and \n both seem to do the same thing but there is a subtle difference between them. 

cout << endl inserts a new line and flushes the stream(output buffer), whereas cout << “\n” just inserts a new line.

Therefore, cout << endl; can be said equivalent to cout << ‘\n’ << flush; 

Some other differences between endl and \n are:  

endl

 \n 

It is a manipulator. It is a character.
It doesn’t occupy any memory. It occupies 1 byte memory as it is a character.
It is a keyword and would not specify any meaning when stored in a string.It can be stored in a string and will still convey its specific meaning of line break.
We cannot write ‘endl’ in between double quotations.We can write ‘\n’ in between double quotations like cout<<“\n”;
It is only supported by C++. It is supported in both C and C++.
It keeps flushing the queue in the output buffer throughout the process. It flushes the output buffer only once at the end of the program

Note: cout << “\n” looks performance wise better but in real cout << endl is much better in C++; As it doesn’t occupies any memory and also if flushing of stream is required.

Example 1: 

We can use endl in C++ but not in C. So endl runs well in C++ but if we use C, it runs error.

C++




#include <iostream>
using namespace std;
 
int main() {
 
    cout << "GFG!"<<endl;  //We can use endl in C++ and it doesn't occupy any memory
      cout << "GFG!";
    return 0;
}
 
//Code submitted by Susobhan AKhuli

C




#include <stdio.h>
 
int main() {
 
    // code
      //We cann't use endl in C
      printf("GFG!",endl);  //So it runs error
      printf("GFG!");
    return 0;
}
 
//Code submitted by Susobhan AKhuli

Output:

GFG!
GFG!

Example 2:

We can use “\n” in both C and C++ but it occupies 1 byte memory.

C++




#include <iostream>
using namespace std;
 
int main() {
 
    cout << "GFG!"<<"\n";
      cout << "GFG!";
    return 0;
}
//Code submitted by Susobhan AKhuli

C




#include <stdio.h>
 
int main() {
 
    // code
      printf("GFG!\n");
      printf("GFG!");
    return 0;
}
 
//Code submitted by Susobhan AKhuli

Output:

GFG!
GFG!

This article is contributed by Akshat Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!