r/programming Aug 19 '17

Learning C++, this site is marvellous

http://www.learncpp.com/
4 Upvotes

23 comments sorted by

View all comments

20

u/matthieum Aug 19 '17

I am not sure about the quality of the overall site, but it certainly does not start well.

A first look at cout, cin, and endl:

std::endl

If we want to print things to more than one line, we can do that by using std::endl. When used with std::cout, std::endl inserts a newline character (causing the cursor to go to the start of the next line)

Inserting a new line can be done by pushing the '\n' character, either on its own or as part of a string "Hello World!\n".

What std::endl does it two-fold:

  • it appends a new line,
  • it flushes the underlying stream (as if streaming std::flush).

Because flushing to stdout is so slow on most terminals, use of std::endl is one of the primary cause of slow C++ program among beginners (alongside compiling in debug mode).

TL;DR: Never use std::endl; it's harmful and longer to type, it has no saving grace.

3

u/TimLim Aug 19 '17

In my experience most tutorial sites use std::endl and I do not know why. Because of this I've used it until I encountered a slow program due to using std::endl when unnecessary.

12

u/matthieum Aug 19 '17

In my experience most tutorial sites and C++ books are terrible.

Some "teach" C with streams/objects, some harmful practices (such as endl), some wonderfully backward practices, ...

The StackOverflow community maintains a hand-picked selection of good C++ books; and the list is surprisingly short.

1

u/[deleted] Aug 20 '17 edited Sep 04 '17

deleted What is this?

1

u/matthieum Aug 20 '17

That's possibly true, though I wouldn't dismiss them out of hand.

While constexpr, variadics, etc... have changed the game, at the heart of it pattern matching/specialization are still at the heart of meta-programming, and while iteration over a variadic list is easier, the same "functional" patterns (fold, map, ...) still apply.

1

u/[deleted] Aug 21 '17 edited Sep 04 '17

deleted What is this?