I understand that the only difference between the two ways of making a new line is that the first one also empties the output buffer. Could you show me a practical example where you can see the difference in using one and the other?
I understand that the only difference between the two ways of making a new line is that the first one also empties the output buffer. Could you show me a practical example where you can see the difference in using one and the other?
Taken from here and from here , explaining the following:
The '\n'
is a character that, called "line break" or "lone feed", is represented by appearing null, but only positions the cursor on a new line to continue writing.
While std::endl
is equivalent to: 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 clean buffer (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 configurations:
clang++ -o endl -O3 endl.cpp && time ./endl >rubbish
Throw 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
Produce these results:
real 0m0.263s
user 0m0.236s
sys 0m0.008s
Response times are much more effective since it does not "require" to clear the buffer.
This, of course, in a hypothetical case where you do not need to clean the output buffer, but as I mentioned above, there is not enough difference between the two, an escape character will always be printed \n
for the new line What leaves one last detail: The only difference is performance.
I hope I help you.