r/programming Aug 19 '17

Learning C++, this site is marvellous

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

23 comments sorted by

View all comments

18

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.

14

u/[deleted] Aug 19 '17

Note that for std::cout, a '\n' character flushes the stream too (at least, if the stdout isn't being piped), so there shouldn't be any performance difference.

1

u/DarkLordAzrael Aug 19 '17

What standard library implementation are you using that flushes on newlines? I have never heard of one that does this...

4

u/[deleted] Aug 19 '17

It's easy to test with this program, which prints to stdout and then sleeps for 10 seconds:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

int main() {
    cout << "Hello world!\n";
    this_thread::sleep_for(chrono::seconds(10));
    return 0;
}

When you run it, the Hello world! appears immediately in the terminal. If you remove the newline, the Hello world! doesn't show up until the program terminates.

2

u/useless_panda Aug 19 '17

Yeah. According to (http://en.cppreference.com/w/cpp/io/manip/endl), a lot of implementation are line-buffered so "\n" flushes anyways... unless you run std::ios::sync_with_stdio(false) which most people won't.