Difference between endl and '\n'

What is the difference between using endl and '\n' to start a new line in the program?

And which is better for use in programs(and why)?
Last edited on
'\n' is a new line.
endl is a new line + a flush.

The below are equivilent:

1
2
3
std::cout << '\n' << std::flush;
//..
std::cout << std::endl;


Flushing the stream ensures whatever you sent is actually output and isn't just sitting in the buffer. This involves a little overhead, so if you want to be super optimal you shouldn't be constantly flushing. However it's important to do if you want to ensure output is visible before a lengthy operation is complete.

For example, try the following:

1
2
3
cout << "1\n";
Sleep(2000);  // wait 2 seconds (#include <windows.h> for Sleep)
cout << "2" << endl;


vs.

1
2
3
cout << "1" << endl;
Sleep(2000);
cout << "2" << endl;



With the \n, even though you're outputting the "1" before you sleep, it [probably] won't be visible until after you sleep.

However with endl, it will display the "1", then wait 2 seconds, then display the "2".


EDIT:

Actually I just tried it on mine and both behave the same way so maybe this is a bad example.

They're not guaranteed to behave the same, though.

Oh well. XD
Last edited on
from what i understood was endl was same as \n but refered to objects
Well, they behaved the same for me as well.
But I understood what you meant.
Thanks for the explanation.
Topic archived. No new replies allowed.