95

It was many years now since I stopped using std::endl to end lines when writing to std::cout, and started using "\n" instead.

But now I start seeing more snippets of code using '\n' instead, and I started wonder what might be best.

Besides the obvious that one is a string, and the other a character, is there any advantage to using this:

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

Over this:

std::cout << variable << "\n";

Late addition:

When I asked this question I seemed to think that newline '\n' flushed the buffer. Now I know that it depends.

By default std::cin is tied to the old C stdin FILE* stream, and std::cout is tied to stdout. The flushing on newline comes from this tying. By default stdout, if connected to a terminal, is line-buffered. That means a new line will flush its buffers. So when printing a newline using std::cout, that will lead to stdout being flushed.

If stdout is not connected to a terminal (for example the output has been redirected or is piped), or if the tie between std::cout and stdout is broken, then newlines will not flush anything.

10
  • 1
    interesting question, I'd also like to see an answer to that question. :) Also, why did you stop using std::endl? Nov 29, 2011 at 12:57
  • @Constantinius stackoverflow.com/questions/213907/c-stdendl-vs-n
    – alex vasi
    Nov 29, 2011 at 12:59
  • 1
    @Constantinius I stopped with using namespace std and std::endl was to much to write. :) Nov 29, 2011 at 12:59
  • 5
    @Joachim: You stopped using it for the wrong reasons, but atleast you stopped using it. ;)
    – Xeo
    Nov 29, 2011 at 13:04
  • 8
    Your edit is misleading. std::endl is documented to flush buffered streams. "Most implementations seem to flush" is another way of saying "I 've been lucky so far" -- but to be fair, this only matters if you care about flush timings (which is very very rare IMHO).
    – Jon
    Nov 29, 2011 at 13:04

6 Answers 6

111

Actually, '\n' should be the default. Unless you want to also explicitly flush the stream (and when and why would you want to do that?), there is no need to use std::endl at all.1
Of course, many books and tutorials use std::endl as the default. That is unfortunate and might lead to serious performance bugs.

I suppose there's little difference between using '\n' or using "\n", but the latter is an array of (two) characters, which has to be printed character by character, for which a loop has to be set up, which is more complex than outputting a single character. Of course, when doing IO this rarely matters, but if in doubt, when you want to output one character literal, output a character literal, rather than a whole string literal.
A nice side-effect of doing so is that you communicate in your code that you intended to output only a single character, and not just accidentally did this.


1 Note that std::cout is tied to std::cin by default, which leads to std::cout being flushed before any input operation, so that any prompt will be printed before the user has to input something.

24
  • 36
    @JohnDibling: '\n' vs. "\n" is certainly a micro-optimization, but why would it be premature? You can write both, so why not write the one that conveys your intention and might be faster and will not be slower? It's the same as with ++it vs. it++: It rarely matters, but when it does, it pays off to be used to writing the one which is faster where it matters.
    – sbi
    Nov 29, 2011 at 14:12
  • 12
    @John: equally though, "\n" is premature pessimization. OK, so it's probably some insignificant amount slower, and that's good because you want to prove that you're wise to the risk of premature optimization by deliberately writing code you think is slow. But you don't know that it's slower, and you have to write something, so which do you choose? Since there's no difference in comprehensibility, I think it's reasonable to write either, for pretty much any reason, including a naive guess that it's possibly some iota faster, or emits smaller code Nov 29, 2011 at 15:07
  • 5
    @JohnDibling: I wasn't explaining my point as clear as I should have. We are not talking about an optimization here. We are talking about picking one of two possibilities, where one is more expressive, unlikely to be slower, and likely to be faster.
    – sbi
    Nov 29, 2011 at 15:08
  • 3
    @John: I think the question is about what habits to get into, i.e. "what should I normally do -- given that the options all look about the same to me, is there any basis at all for a rule of thumb?". Naive guesses about performance are as good a tie-breaker as any IMO. As far as avoiding std::endl is concerned, I think that "don't tell the program to do extra work that you don't want" is a perfectly reasonable rule of thumb even in the absence of profiling. It's then a bit hair-splitty whether "\n" is in the same category, whether a string literal is in a sense "more" than a char literal. Nov 29, 2011 at 15:18
  • 7
    @John: ++it vs. it++ doesn't matter at all in 99.99% of all cases. But since it doesn't matter, why not make a habit of using the one that's faster in those 0.01%? There's many cases where you need to pick a default: making one-arg ctors explicit, making functions const, pre- vs. post-increment, '\n' vs. std::endl,... Why not trying to always do the one that has an advantage, no matter how rarely the cases are and how marginally the advantage? If you can pick either one, why not pick the one that has an advantage in 0.01%, if it has no disadvantage in the remaining 99.99%?
    – sbi
    Nov 29, 2011 at 21:08
17

There are no the best. You use what you need :

  • '\n' - to end the line
  • "some string\n" - the end the line after some string
  • std::endl - to end the line and flush the stream
2
  • What is the simplest explanation of "flushing the stream"? Thank you so much in advance!
    – Milan
    Nov 17, 2021 at 21:06
  • 2
    @Milan Imagine water flowing down a pipe. Flushing the stream pushes the water though and waits for it all to get through the pipe before sending more water in. Except that, the water cant move through until the recipient wants it, so you have to wait for the recipient to suck the water out of your pipe so you can flush more water down. This is why is rarely a good idea to flush your pipes with endl, so '\n' should be used.
    – Jack G
    May 16, 2022 at 21:59
15

They do different things. "\n" Outputs a newline (in the appropriate platform-specific representation, so it generates a "\r\n" on Windows), but std::endl does the same and flushes the stream. Usually, you don't need to flush the stream immediately and it'll just cost you performance, so for the most part there's no reason to use std::endl.

4

Edit: I worded my answer poorly, which may have lead people to believe that I thought "\n" actually printed a null character. This is of course wrong :)

Edit 2: Having looked at a C++ reference, chars are passed by reference anyway, so there's no difference there. The only difference is that the cstring will have to be searched for a delimiting character. The below isn't correct due to this fact.

'\n' would be ever so slightly more efficient than "\n", because the latter also contains a null character on the end, which means you're sending a char* to operator<<() (usually 4 bytes on a 32-bit system) as opposed to a single byte for a char.

In practice, this is borderline irrelevant. Personally, I follow the convention that Vladimir outlined.*

15
  • 1
    Because it's a cstring. A single char ('\n') will take up 1 byte, whereas cstrings are implicitly appended with a null character, hence "\n" is actually "\n\0". It's a trivial issue nonetheless. For example, sizeof("\n"); returns 2 on my machine. Nov 29, 2011 at 13:13
  • 2
    Again, no. The string "\n" (with the terminating null) has static storage duration, it doesn't ened to be constructed at runtime at all.
    – jalf
    Nov 29, 2011 at 13:40
  • 2
    @jalf But still there is a cost for iterating over an array of chars until the '\0' is found. Nov 29, 2011 at 13:50
  • 1
    @ChristianRau: Yeah, but in the case of "\n" vs '\n' that cost would be very minimal. Nov 29, 2011 at 13:53
  • 1
    @ChrisParton Of course we're all speaking about minimality here, but your answer wasn't completely wrong and there is indeed a performance difference between '\n' and "\n". Nov 29, 2011 at 14:00
4
  • std::cout << variable << std::endl;

    std::endl output a newline, but it also flushes the output stream. In other words, same effect as

    std::cout << variable << '\n'; // output newline
    std::cout.flush();      // then flush 
    
  • std::cout << variable << '\n';

    '\n' output a newline for a char, hence ostream& operator<< (ostream& os, char c); will be used.

  • std::cout << variable << "\n";

    "\n" is a const char[2], so ostream& operator<< (ostream& os, const char* s); will be used. We can imagine, this function will contain a loop, we might argue is overkill to just print out a newline.

3

std::endl flushes the stream. When this something you want to happen -- e.g. because you expect your output to be made visible to the user in a timely fashion -- you should use std::endl instead of writing '\n' to the stream (whether as an isolated character or part of a string).

Sometimes, you can get away without explicitly flushing the stream yourself; e.g. in a linux environment, if cout is synchronized with STDOUT (this is the default) and is writing to a terminal, then by default, the stream will be line buffered and will automatically flush every time you write a new line.

However, it is risky to rely on this behavior. e.g. in the same linux environment, if you decide to run your program with stdout being redirected to a file or piped to another process, then by default, the stream will be block buffered instead.

Similarly, if you later decide to turn off synchronization with stdio (e.g. for efficiency), then implementations will tend to use iostream's buffering mechanisms, which doesn't have a line buffering mode.

I have seen much wasted productivity due to this mistake; if output should be visible when it is written, then you should either use std::endl explicitly (or use std::flush or std::ostream::flush, but I usually find std::endl more convenient), or do something else that ensures flushing happens often enough, such as configuring stdout to be line buffered (assuming that's adequate).

Not the answer you're looking for? Browse other questions tagged or ask your own question.