Both serve the same purpose, putting a new line. The only difference is that endl causes flushing of the output buffer everytime it is called where as ‘\n’ does not.
So, if you are writing al the alphabets of English to a file using the following code,
#include <iostream>;
#include <fstream>;
using namespace std;
int main()
{
ofstream MyFileStream("Alphabets.txt", ios:: out);
for (char Index = 'A'; Index <= 'Z'; ++Index)
{
MyFileStream << Index << endl;
}
return 0;
}
the output buffer will be flushed 26 times while the same code with ‘\n’ instead of endl will cause it to be flushed only once and that is when the program exits (assuming that the output buffer is larger than 26 bytes).
Some Background Info
- Anything to be output is first queued into an output buffer and written to the device (hard disk, monitor etc…) when the queue is full. Of course, this is to ensure speed of execution as the access to the external device is less frequent.
- If you are in a situation where you have to avoid buffering, you can use std::endl instead of ‘\n’. An example of the above situation is when you are using old style debugging using multiple cout statements between code lines to see where exactly a crash occurs.
Thank you, I did not know this. I have always had this feeling that my code ran faster when using \n rather than endl (when outputting a couple hundred-thousand lines), but I had always written it off as superstition.
Alexander, use a high res timer instead to verify. Your internal body clock does not have a very high resolution
gl & hth
You have got to be kidding me right? \n will give you a better performance? How about you try this sample program.
#include
using namespace std;
int main()
{
for (unsigned short int i = 0; i <= 50000; ++i)
{
cout << i;
//cout << "\n";
cout << endl;
}
return 0;
}
run this three times and work out the average speed, then comment out the endl line and uncomment the \n line and do the same. The \n was .029 seconds faster with writing 50000 lines, how many lines are output in your typical program?