1

My answer, today, was edited and std::endl was changed to \n.

Does \n have any advantages?

Community
  • 1
  • 1
khajvah
  • 4,889
  • 9
  • 41
  • 63
  • Weird, I searched but couldn't find – khajvah Oct 08 '13 at 10:57
  • Anyway I would mark that edit as invalid. If someone thinks that you should modify the code in your answer, they should have left a comment for you to consider. Modifying your code risks making your answer mistaken, if they are wrong. – SJuan76 Oct 08 '13 at 11:10
  • @SJuan76 The code in my answer really doesn't need `std::endl`(It doesn't need to `flush` the `stream`), so I am good with that edit. – khajvah Oct 08 '13 at 11:13
  • 1
    @khajvah Edit it back. If you wanted `std::endl`, then no one should change it by editing to something you didn't want. (In general, when answering questions here, `std::endl` is probably better, since it's what is more usually wanted.) – James Kanze Oct 08 '13 at 11:15
  • 1
    @SJuan76 I agree. This is absolutely abuse of editing. I've had to edit my own back once or twice for similar reasons. – James Kanze Oct 08 '13 at 11:16
  • @JamesKanze It's not about `wanting`. At the time of my answer, I didn't know the difference, so just randomly chose `std::endl`. In case of my answer, it is more reasonable to use `\n` but still, editing to `\n` and commenting `use \n` isn't helpful. Editor should have explained better. – khajvah Oct 08 '13 at 11:20
  • 1
    @khajvah In the context of your answer, `std::endl` is better. In general, unless there is a specific reason not to, `std::endl` is to be preferred, especially for output which will probably end up on a terminal. About the only time you want to use `'\n'` is when outputting large quantities of data in a block. – James Kanze Oct 08 '13 at 11:56

3 Answers3

4

std::endl calls flush stream while cout << "\n" does not flush the stream, so cout << "\n"; gain better performance, especially while you call it in loop.

§27.7.3.8 Standard basic_ostream manipulators

namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}
1 Effects: Calls os.put(os.widen(’\n’)), then os.flush().
billz
  • 44,644
  • 9
  • 83
  • 100
0

Yes, it doesn't flush the stream which can be a huge time burden.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

\n terminates the line. std::endl terminates the line and flushes the output buffer. In most cases, continually flushing the output buffer merely wastes time.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • 1
    In most cases, _not_ continually flushing the output buffer wastes the developer's time, since it gives a false idea of how far the program has gotten before it crashes. – James Kanze Oct 08 '13 at 11:58
  • @JamesKanze - relying on the wrong tool wastes developer's time. If you need progress reports, by all means flush buffers. – Pete Becker Oct 08 '13 at 13:28