Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"std::endl" vs "\n"

Many C++ books contain example code like this...

std::cout << "Test line" << std::endl; 

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test line\n"; 

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?

like image 985
Head Geek Avatar asked Oct 17 '08 21:10

Head Geek


People also ask

Is \n or Endl better?

What is the difference between endl and \n in C++? Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not.

Which is faster \n or Endl in C++?

The difference is obvious. The second one is much faster. std::endl always flush es the stream. In turn, \n simply puts a new line character to the stream, and in most cases this is exactly what we need.

Is Endl slower than \n?

Endl flushes the output buffer and '\n' doesn't. if you want the buffer flushed frequently, use '\n'. if you do, use endl. Endl is actually slower because it forces a flush, which actually unnecessary.

Does STD Endl flush?

std::endl writes a newline to the output stream and flushes it. In most cases, the developer doesn't need to flush. Flushing operation is expensive, because it involves a system call.


2 Answers

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

like image 191
David Thornley Avatar answered Sep 20 '22 06:09

David Thornley


The difference can be illustrated by the following:

std::cout << std::endl; 

is equivalent to

std::cout << '\n' << std::flush; 

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \n if you are worried about performance (which is probably not the case if you are using the << operator).

I use \n on most lines.
Then use std::endl at the end of a paragraph (but that is just a habit and not usually necessary).

Contrary to other claims, the \n character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin and std::cout being special but still files (or file-like)).

like image 28
Martin York Avatar answered Sep 21 '22 06:09

Martin York