Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
endl in C++
2.1.
Working of C++ endl 
3.
“\n” in C++
4.
Implementation of endl vs \n in C++
4.1.
Flushing the output stream 
5.
endl vs \n in C++ 
6.
Frequently Asked Questions
6.1.
What is C++? 
6.2.
What are the advantages of C++? 
6.3.
What is Function Overriding?
6.4.
What is a storage class?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference between "endl" and "\n" in c++

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

endl and “\n” are used for inserting the new line in C++. However, there is a difference between them, when endl is encountered, the operating system flushes the output buffer and inserts a new line while “\n” just inserts a new line. 

Introduction

To understand it in more detail, continue reading this blog; you will get a clear idea of endl vs \n in c++.  

Also, see Literals in C.Fibonacci Series in C++
 

endl in C++

A predefined object of the iostream class is used for inserting the new line characters while flushing the stream is endl in C++. This endl is similar to \n and performs the functionality of inserting the new line characters, but \n does not flush, whereas endl does the job of inserting new line characters while always flushing the stream. Hence the statement cout<<endl; is equal to the statement cout<< ‘\n’ << flush; meaning that a new line character can be used along with flush explicitly becomes equal to the endl statement in C++.

Working of C++ endl 

  • Whenever the program writes the output data to the stream, all data will not be written to the terminal. Instead, it will write to the buffer until all enough data is collected in the buffer to output to the terminal.
     
  • But if we use it to flush the program, the entire output stream will be flushed to the terminal without storing anything in the buffer.
     
  • Whenever we insert a new line character to display in the next line while flushing the stream, we can use endl in C++.
     
  • Whenever there is a need to insert the new line character to display the output in the next line, we can use endl in ‘\n’ character, but it does not do the job of flushing the stream. So if we want to insert a new line character along with flushing the stream, we use endl in C++.
     
  • Whenever the program writes the output data to the stream, all the data will not be written to the terminal. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

“\n” in C++

The other way to break the line in C++ is to use the newline character — \n. 

Unlike endl, \n must be within quotes. You can write “\n” by itself, and you can also insert the newline sequence in the middle of a string. 

#include <bits/stdc++.h>
using namespace std;
int main()
{
    cout << "This is line first.\nThis is line second.";
    return 0;
}

 

The Code will recognize the escape function and create a new line accordingly. 

This is line first.
This is line second.

Implementation of endl vs \n in C++

Endl and \n are different in terms of syntax because endl is a function, it must stand alone in the cout statement following an extraction operator (<<). You should also not use endl with quotes since this would cause the program to output endl as a string.

While \n must appear either within double quotes (“ “) or single quotes (‘ ‘). You can also place \n in the middle of a cout statement without inserting any additional formatting. Failing to place \n in quotes will result in a compilation error.

Here we see both new lines commands used in the same block of code:

// endl vs \n in C++ 
#include <bits/stdc++.h>
using namespace std;
int main()
{
    cout << "This is line first.\nThis is line second." << '\n';
    cout << "This is line third." << endl
         << "This is line fourth." << endl;
}

 

With two cout statements, we get this output:

This is line first.
This is line second.
This is line third.
This is line fourth.

 

Flushing the output stream 

When a program executes the endl function, it flushes the output buffer. Since pulling from the output buffer is time-consuming, having the program write an output every time endl is called adds a significant amount to run time.

\n does not flush the output buffer. Since cout automatically performs a flush, the program writes the entire output simultaneously, reducing run time.

For smaller code, you probably won’t notice the difference. Lengthy or cumbersome programs, however, will see a considerable difference.

The example below shows a for loop that increments a counter 10,000,000 times. A built-in timer tracks how long the program takes to complete its run time. See the example below.
 

// endl vs \n in C++ 
#include <bits/stdc++.h>
using namespace std;
int main()
{
    auto begin = std::chrono::high_resolution_clock::now();
    int iter = 1000000;
    for (int i = 0; i < iter; i++)
    {
        cout << endl; // endl is replaced by '\n' to test the difference
    }


    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);
    return 0;
}

 

Output 

With endl: Time measured: 1282.024 seconds.
With \n: Time measured: 1266.650 seconds.


As you can see, the program using \n runs 16 seconds faster, but there isn’t an order-of-magnitude difference between the two run times.

Also Read - C++ Interview Questions

endl vs \n in C++ 

endl 

\n 

endl is a manipulator  \n in character. 
It does not occupy any memory. Since it is a character, it occupies 1 byte of memory. 
It is a keyword and has no meaning when placed in a string.  It will still convey the same meaning as a line break even if it is stored as a string.
'endl' cannot be inserted between double quotes.  \n can be inserted between double quotes. 
Only supported in C++  Supported in both C and C++
The output buffer's queue is flushed repeatedly throughout the process.  The output buffer's queue is flushed once at the end of the program. 

Frequently Asked Questions

What is C++? 

C++ is an object-oriented programming language introduced to overcome the jurisdictions where C was lacking. Object-oriented works with polymorphism, inheritance, abstraction, encapsulation, object, and class. 

What are the advantages of C++? 

C++ is an OOPs language which means the data is considered as objects and a multi-paradigm; It means that we can write the program's logic, structure, and procedure, and memory management is the key feature.  

What is Function Overriding?

When a function of the same name, the same arguments or parameters, and the same return type are already present/declared in the base class is used in the derived class is known as Function Overriding. It is an example of Runtime Polymorphism or Late Binding, meaning the overridden function will be executed at the run time of the execution.

What is a storage class?

A storage class in C++ specifically resembles the scope of symbols, including the variables, functions, etc. Some of the storage class names in C++ include mutable, auto, static, extern, register, etc.

Conclusion

In this blog, we discussed endl and \n in detail, the implementation of endl and \n, and endl vs \n in c++. In endl vs \n in c++, we discussed major differences between their syntaxes and implementations. 

Recommended Reading:

Yarn vs NPM

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations. Read our blogs on aptitudecompetitive programminginterview questionsIT certifications, and data structures and algorithms for the best practice.

Previous article
Top C++ Projects for Beginners
Next article
Virtual Functions & Runtime Polymorphism in C++
Live masterclass