0

I just started learning C++ and I noticed that when I do cout << "Some text" << endl; endl is not bold. I want to make sure that this is not a problem and it won't cause any future problems.

peterh
  • 11,875
  • 18
  • 85
  • 108
aku181
  • 1
  • 1
    Does it insert a newline? If yes, why should it be a problem? – nbro Dec 21 '14 at 02:06
  • 1
    @nbro: *ouch*… a common misunderstanding is that `endl` is what you use when you want a newline… `'\n'` is there for that particular purpose. `std::endl` does two things, it adds a newline and it *flushes* the stream, which can cause a performance penalty. A friend taught me that you should never use `endl`, but rather `'\n'` for newline, and if you want to *flush*, do it explicitly with `std::flush` – David Rodríguez - dribeas Dec 21 '14 at 02:23
  • @DavidRodríguez-dribeas Why is there a `std::endl` then? – nbro Dec 21 '14 at 02:35
  • 1
    @nbro: It was initially added to create similar behavior for streams as setting `_IOLBF` on a stream. The assumption was that it would be used where a newline and a flush would be needed and nowhere else. Instead, people advertised it in books as a way spell newline! This misrepresentation resulted in a lot of C++ code interacting with files being extremely slow. So far I have found severe performance problems related to inappropriate use of `std::endl` at three major locations I have worked at (out of a total of 5 where at two of them the code in the project wasn't really using C++...). – Dietmar Kühl Dec 21 '14 at 02:46

1 Answers1

1

Do not (<---- this intentionally bold!) use std::endl! Ever. It has no place in C++. It was a good idea but it is being abused. If you want a newline, use '\n'. If you want a flush, use a std::flush. Here is a more thorough explanation.

I don't know about Eclipse but I'd assume that it highlight keywords in bold: std::endl isn't a keyword. It is just a function (well, actually it is a function template but the details really don't matter) with a specific signature (std::ostream&(std::ostream&)) pointers to which are treated special when using it with an output operator on a std::ostream: the operator will just call the function with the stream as argument. These functions are called manipulators.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Thanks for the explanation of the `endl` stuff, I did not know about it :D – nbro Dec 21 '14 at 02:50
  • The only reason I asked is because I saw this video and wondered why mine wasn't bold https://www.youtube.com/watch?v=1Enqpi4trl8&list=PLmpc3xvYSk4wDCP5zjt2QQXe8-JGHa4Kt&index=4 Thanks for the explanation. – aku181 Dec 21 '14 at 03:05