C++: std:endl VS \n

Question:

I understand that the only difference between the two ways of making a new line is that the first one also flushes the output buffer. Could you show me a practical example where you can see the difference in using one and the other?

Answer:

Taken from here and here , explaining the following:

The '\n' is a character that, called a "line break" or "lone feed", is represented by looking like null, but only positions the cursor on a new line to continue typing.

Whereas std::endl is the equivalent of: std::cout << "\n" << std::flush .

Their differences are strictly obvious, since calling the \n character only involves concatenating a single string, but using std::endl calls a buffer clean (which answers your question) .

The cases where they can be used, let's try with the code of the first link:

#include <string>
#include <iostream>

int main() {
    std::string s(1, 'x');
    for (int i = 0; i < 1000000; ++i) {    
        std::cout << s << std::endl;
    }
    return 0;
}

With the following settings:

clang++ -o endl -O3 endl.cpp && time ./endl >rubbish

Returns the following results:

real    0m4.518s
user    0m1.080s
sys     0m3.311s

While the same code only with the escape:

#include <string>
#include <iostream>

int main() {
    std::string s(1, 'x');
    for (int i = 0; i < 1000000; ++i) {
        std::cout << s << '\n';
    }
    return 0;
}

And the same settings:

clang++ -o endl -O3 endl.cpp && time ./endl >rubbish

Produces these results:

real    0m0.263s
user    0m0.236s
sys     0m0.008s  

Response times are much more effective since the buffer is not "required" to be cleaned.

This, of course, in a hypothetical case where you don't need to clear the output buffer, but as I mentioned earlier, there is not enough difference between the two, an escape character \n always be printed for the new line. Which leaves one last detail: The only difference is performance.

I hope it helps you.

Scroll to Top