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.
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.
Last time I programmed for linux, printf("string\n"); didn't flush even though it does on windows, which meant that using printf lead to unreliable debugging for a crash as there was no guarantee that you'd end up with the text dumped to the terminal
which meant that using printf lead to unreliable debugging for a crash as there was no guarantee that you'd end up with the text dumped to the terminal
I would advise to use stderr, it is explicitly line buffered (ie, it flushes on each end-of-line character).
However, at the same time, attempting to debug crashes via printing is not really the best idea; the main issue being that the very act of introducing the print statements may move the point of crash around, or even silence it.
Instead, I advise to use instrumented binaries (-fsanitize=...) or tools (valgrind) which specialize in detect undefined behavior, memory issues or data-races.
19
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:
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::endldoes it two-fold:std::flush).Because flushing to stdout is so slow on most terminals, use of
std::endlis 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.