Чем отличается endl от n
Перейти к содержимому

Чем отличается endl от n

  • автор:

Difference between «endl» and «\n» [duplicate]

There’s rarely any practical difference. Except that endl will flush the stream. Unless you absolutely need to flush the stream you can use either of them.

Dec 22, 2010 at 19:03

Use std::endl if this has any interaction with the user. But prefer ‘\n’ if you are just building an offline file or something.

Dec 22, 2010 at 19:07

1 Answer 1

Yes, they’re different.

«\n» is just a string of length 1 that gets appended to stdout.

std::endl , instead, is an object that will cause to append the newline character ( «\n» ) AND to flush stdout buffer. For this reason it will take more processing.

answered Dec 22, 2010 at 18:57
25.8k 20 20 gold badges 99 99 silver badges 151 151 bronze badges

Actually, it can be different, but it doesn’t have to be. Most consoles are line buffered which means they’re going to get flushed on the newline whether or not you explicit flush on your own,

Dec 22, 2010 at 19:04

ostream has its own buffer too, so the console being line buffered isn’t the only factor here, I think. If ostream doesn’t flush after it placed the ‘\n’ into its buffer, the console won’t ever see the newline.

Dec 22, 2010 at 19:21

[Nitpicking Mode On] ‘\n’ is a char and «\n» is a string of length 1. Writing a char to the buffer could be faster in some cases. [Nitpicking Off]

Dec 22, 2010 at 19:45

In my last job, an unnamed number of years ago, we had an occasion (writing a large text file) in which changing from endl for each line to «\n» for them made a very noticeable difference — from a ~2s pause when saving down to no user-detectable pause when saving.

std::endl vs \n in C++

std::endl and \n both seem to do the same thing but there is a subtle difference between them.

Though in some use cases like competitive programming, it is better to use “\n” when the problem is not interactive, as it saves time by not flushing the entire line and thus improves the time complexity of the program.

Some other differences between endl and \n are:

Explanation for the last point of difference :

Suppose you have a C++ program that writes some output to the console using the std::cout stream. You want to print the message “Hello World” followed by a new line character.

If you write the following code:

The output buffer will not be flushed immediately, and the message will be stored in the buffer until the program finishes. This can be more efficient if you’re writing a lot of output to the console, because flushing the buffer can be an expensive operation.

However, if you write the following code instead:

The output buffer will be flushed immediately, which means that the message “Hello World” will be written to the console right away. This can be useful if you want to make sure that the output is displayed immediately, for example if you’re writing a progress indicator or a status message.

In summary, using std::endl in C++ will flush the output buffer and write the data to the output device immediately, while using \n will not flush the output buffer until it is necessary or manually triggered.

Example 1:

We can use std::endl in C++ but not in C. So std::endl runs well in C++ but if we use C, it runs error.

Output:

GFG!
GFG!

Example 2:

We can use “\n” in both C and C++ but it occupies 1 byte memory.

Output:

GFG!
GFG!

«std::endl» vs «\n»

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

std::cout  

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?
4,857 35 35 gold badges 34 34 silver badges 48 48 bronze badges
asked Oct 17, 2008 at 21:25
39.2k 22 22 gold badges 78 78 silver badges 88 88 bronze badges
Good explanation: cppkid.wordpress.com/2008/08/27/why-i-prefer-n-to-stdendl
– Payton Millhouse
Oct 17, 2008 at 21:28
@derobert this one is older than the other
Nov 13, 2013 at 15:31

@HediNaily indeed it is. But the answer on the other one strikes me as slightly better, so I picked to do it that way around. Also, the other one is slightly broader, also covering '\n' .

Nov 13, 2013 at 15:35

If you intend to run your program on anything else than your own laptop, never ever use the endl statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use of endl is know to kill networked file systems like NFS.

Oct 27, 2018 at 23:32
stackoverflow.com/a/30968225/3163618 there may be a significant performance difference.
Mar 24, 2020 at 4:38

12 Answers 12

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 .

13.4k 17 17 gold badges 71 71 silver badges 126 126 bronze badges
answered Oct 17, 2008 at 21:56
David Thornley David Thornley
56.7k 9 9 gold badges 92 92 silver badges 159 159 bronze badges

Or consider using ::std::cerr instead of ::std::cout since it's unbuffered and flushed with each and every output operation.

Jan 23, 2010 at 11:45

@Omnifarious: No std::cerr should be reserved for errors. The two streams are not synced together so if you output some text to cout it may be buffered and the cerr will go direct to the output this resulting in a mixed mode display. Use cerr for what it is supposed to be for (errors) and cout for what it is designed for (normal interaction).

Feb 3, 2010 at 16:39
@Lucas: No more than '\n' is platform aware.
Feb 17, 2010 at 7:39

@LokiAstari: I wouldn't say stderr is for "errors". Rather, it's for out-of-band diagnostic messages, if you will. It should be possible to say ./prog > file and store only the true program payload, but the program may like to output a lot more status information, even in normal interaction.

Nov 28, 2011 at 3:01

"In many implementations, standard output is line-buffered, and writing '\n' causes a flush anyway, unless std::cout.sync_with_stdio(false) was executed." copied from here

Aug 13, 2013 at 21:01

The difference can be illustrated by the following:

std::cout  

is equivalent to

std::cout  
  • 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

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)).

4,415 1 1 gold badge 20 20 silver badges 37 37 bronze badges
answered Oct 17, 2008 at 22:43
Martin York Martin York
261k 86 86 gold badges 338 338 silver badges 568 568 bronze badges

In many cases, the "see the output immediately" is a red herring, since cout is tied to cin , meaning that if you read input from cin , cout will be flushed first. But if you want to display a progress bar or something without reading from cin , then sure, flushing is useful.

Mar 30, 2011 at 5:55

@LokiAstari: if you are using the - why? I didn't know that operator
Jan 22, 2014 at 7:33

@legends2k: There is an old wives tale that C++ streams are not as performant as C printf(). Though true to an extent the main difference in speed is caused by people using C++ streams incorrectly. stackoverflow.com/a/1042121/14065 In C++ remember to unsync iostreams with C-streams sync_with_stdio(false) and don't flush your output continuously. Let the library work out when to do it. stackoverflow.com/a/1926432/14065

Jan 22, 2014 at 19:53
@Loki: There's an urban legend that sync_with_stdio makes iostreams as fast as stdio. It does not
Sep 15, 2015 at 16:30

@BenVoigt: I was careful with my wording above (so I am happy with them). It is not as performant as stdio (because it does more). BUT a lot of the performance gap people complain about is cause by sync with stdio.

Sep 15, 2015 at 20:43

There might be performance issues, std::endl forces a flush of the output stream.

58.8k 37 37 gold badges 184 184 silver badges 265 265 bronze badges
answered Oct 17, 2008 at 21:28
Martin Beckett Martin Beckett
95.5k 28 28 gold badges 192 192 silver badges 266 266 bronze badges
And it can do any other processing that the local system requires to make this work well.
Oct 17, 2008 at 21:32

There's another function call implied in there if you're going to use std::endl

a) std::cout  

a) calls operator b) calls operator
8,058 8 8 gold badges 61 61 silver badges 67 67 bronze badges
answered Nov 17, 2009 at 22:29
427 4 4 silver badges 2 2 bronze badges

It may be obvious, but it has a huge impact on threaded programs where, generally, the first version will write a single line in one shot where the second version may be split by writes from other threads. Often enough I find myself writing std::cout
Jun 22, 2011 at 23:15
What about std::cout << "Hello" << "\n"; ? Feb 22, 2018 at 20:39

@byxor Almost the same except the buffer flushing as described in other answers. Anyway, it's redundant when you can merge the two string literals into one.

Apr 19, 2018 at 6:44
Nov 22, 2018 at 14:30
Lol no, that is not the reason I use \n.
Feb 27, 2019 at 10:27

I recalled reading about this in the standard, so here goes:

See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.

ISO/IEC 9899:201x

7.21.3 §7

At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

7.21.3 §3

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

This means that std::cout and std::cin are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.

However, if std::cout.sync_with_stdio(false) is called, then '\n' will not cause a flush even to interactive devices. Otherwise '\n' is equivalent to std::endl unless piping to files: c++ ref on std::endl.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *