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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    interesting question, I'd also like to see an answer to that question. :) Also, why did you stop using `std::endl`? – Constantinius Nov 29 '11 at 12:57
  • @Constantinius http://stackoverflow.com/questions/213907/c-stdendl-vs-n – alex vasi Nov 29 '11 at 12:59
  • 1
    @Constantinius I stopped with `using namespace std` and `std::endl` was to much to write. :) – Some programmer dude Nov 29 '11 at 12:59
  • @alex vasi, Joachim Pileborg: thanks, nice to know. – Constantinius Nov 29 '11 at 13:02
  • @constantinius: http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html – Joe Nov 29 '11 at 13:03
  • There may be a slight performance difference between the two (though I wouldn't guess which is faster) but you're doing (slow) I/O already, so it hardly matters. And `'\n'` would probably be better in a very memory-tight environment but it's unlikely you'd be using std::anything in such a case. – Hot Licks Nov 29 '11 at 13:03
  • 5
    @Joachim: You stopped using it for the wrong reasons, but atleast you stopped using it. ;) – Xeo Nov 29 '11 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 '11 at 13:04
  • @HotLicks: it might matter a lot, see the story I linked to in [my answer](http://stackoverflow.com/a/8311177/140719). – sbi Nov 29 '11 at 13:12
  • Do most implementations flush `std::out` on newline even when it's writing to a file, or do they detect when it's a terminal and act accordingly? – Steve Jessop Nov 29 '11 at 15:13

6 Answers6

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.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
  • `'\n'` can in certain situations really be measurably faster than `"\n"`. So it should be a habit to use that, but of course when you want it to be part of a string `"foobar\n"` is the way to go. It might also make sense to -- when your implementation provides a way -- turn of autoflush for `\n`, which will speed up certain things even more. To make things round, `std::cerr` is unbuffered and there is not really a difference then, but for `std::clog` there is of course. – PlasmaHH Nov 29 '11 at 13:47
  • 1
    OTOH, if you want to indicate progress by outputting "...", you might want to call `flush` after each `'.'`! – curiousguy Nov 29 '11 at 13:49
  • @curiousguy: Yeah, that's a valid example for when you really want to flush the stream. IME, those are rare, though. – sbi Nov 29 '11 at 13:51
  • There is a lot of premature micro-optimization going.g on here. – John Dibling Nov 29 '11 at 14:01
  • @PlasmaHH "_turn of autoflush for \n_" what do you mean? – curiousguy Nov 29 '11 at 14:03
  • 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 '11 at 14:12
  • It's premature because it has not been proved that inserting `"\n"` vs inserting `'\n'` is a bottleneck in the code. Profile first, them optimize. – John Dibling Nov 29 '11 at 14:38
  • 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 – Steve Jessop Nov 29 '11 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 '11 at 15:08
  • @Steve: I'm not trying to prove anything. The point that I really had in my mind, but completely failed to convey, is that this simply isn't worth fretting over until the profiler tells you to. You're right -- I don't really know that one is slower than the other. Your question, "Which do you choose?" hits the nail right on the head. That's the big question, and my default answer would be, "Do what you would normally do." (continued...) – John Dibling Nov 29 '11 at 15:14
  • (...continued from above) That might seem a bit open-ended -- it's certainly open to interpretation. For my part, I always insert single chars as single chars -- so, ironically, that's what I'd do here, too. The reason I would do this for `'\n'` is because I'd do it for `char c = 'A';` -- not because `'\n'` might be marginally faster. – John Dibling Nov 29 '11 at 15:15
  • @sbi: I see. I agree with the idea to "[pick] one of two possibilities, where one is more expressive." However, once you added the criteria "unlikely to be slower, and likely to be faster" without having demonstrated that this is a real problem with respect to performance, that's where I diverge. – John Dibling Nov 29 '11 at 15:17
  • 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. – Steve Jessop Nov 29 '11 at 15:18
  • 1
    @sbi: I fall on the same side with `++it` vs `it++` as well. There was a time, long ago, when I was naive enough to believe that `++it` "is faster" than `it++` -- so I established my norm to be to use `++it` in all cases unless I had a reason not to. Now I know "better," and while I still use `++it` as a matter of course, it's not because of performance anymore. Now it's simply because *that's what I always do*. – John Dibling Nov 29 '11 at 15:21
  • @SteveJessop: You're right -- at the end of the day, it really doesn't matter a whole lot. It surely doesn't matter as much as it would seem, given the energy the three of us are investing in to this conversation. I agree completely about using a naive guess about **whatever** is as good a criteria as any when deciding what your personal coding standards are. That's exactly what I did with `++it` vs `it++`. Nevertheless, it's still kind of fun to talk about. – John Dibling Nov 29 '11 at 15:24
  • @John: agreed, I think the interest is the meta-level of how we develop our coding idioms, rather than anything to do with `'\n'` or `"\n"`. Anybody who cared about any possible performance difference between the two could have at least attempted to test it by now, but it's much more interesting to talk about programming in general! – Steve Jessop Nov 29 '11 at 15:30
  • This conversation has convinced me to alter my approach to establishing new personal coding standards. Yesterday, naive guesses about performance would never have entered in to the equation. Moving forward, however, I will not dismiss those naive guesses out-of-hand, and will let them be a potential variable in the consideration set. – John Dibling Nov 29 '11 at 15:36
  • 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 '11 at 21:08
  • 1
    @sbi: In your answer far far above, you mention that "\n" is an array of two characters that must be looped over, which is of course technically correct but could be misleading to a novice. Only the \n itself is output, the second char (a terminating \0) is not. Of course on some platforms (DOS/Windoze) the \n itself is translated on output to two chars (\r followed by \n), but that occurs regardless of whether the caller sent a '\n' char literal or "\n" string literal. – phonetagger Apr 18 '12 at 20:31
  • 1
    BTW, I am *totally* with you on the "given two options of equal difficulty, you might as well pick the one more likely to result in more efficient code" thing. It seems like some folks purposefully pick the way more likely to result in less efficient code just so they can grin deviously & pull out their self-righteous soapbox about premature optimizations whenever someone comments that there's a simple twist in coding technique that's likely to be more efficient, and once adopted and second nature, may add up to a nontrivial savings over the course of a large project. – phonetagger Apr 18 '12 at 20:40
  • @phonetagger: Even an array with only one element is an array, and its processing needs the initialization of a loop variable, the loading of branching code into the pipeline, and whatnot. – sbi Apr 20 '12 at 08:18
  • @sbi: Good grief. I understand that. My point was that your answer seems to suggest that though there's little difference between using '\n' or "\n", the latter is "an array of (two) characters, which has to be printed character by character...". My point was simply that no more actual characters are output on the stream by using "\n", either way, the same number of characters are placed on the stream itself. Regardless, the stream output overhead dwarfs the char array looping overhead by several orders of magnitude. But regardless of that, I was still agreeing with you in principle. – phonetagger Apr 26 '12 at 21:49
  • @phonetagger +1 for your second last comment. This whole discussion was obviuously in need for such an agressively sarcastic comment. You don't need a profiler to check simple and valid reasonings about efficiency. We indeed shouldn't expect an actual performance improvement from such a minor change, but neither should we give ourselves dumber than we really are. – Christian Rau Aug 17 '12 at 11:30
  • @ChristianRau: I have seen cases where inserting a `NOP` statement made code faster — something that certainly goes against all "simple and valid reasoning". I agree with the rest of what you said — which shouldn't be surprising, because, basically, it agrees with what I had said... `:)` – sbi Aug 17 '12 at 11:39
16

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
BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • What is the simplest explanation of ***"flushing the stream"***? Thank you so much in advance! – Milan Nov 17 '21 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 '22 at 21:59
14

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.

jalf
  • 243,077
  • 51
  • 345
  • 550
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.

zangw
  • 43,869
  • 19
  • 177
  • 214
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.*

Chris Parton
  • 1,052
  • 9
  • 16
  • because it's wrong? Why would `\n` generate a null character? – jalf Nov 29 '11 at 13:10
  • 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. – Chris Parton Nov 29 '11 at 13:13
  • So? If I write `std::cout << "hello " << "world", then what will actually be printed will have a null character in the middle of it? I think not. :) The string "\n" is null-terminated, sure, but when that string is writtten to a stream, the null byte is not written. Anything else would be crazy and lead to null bytes scattered all over your strings. The null byte is not part of the string, it is used to delimit it. – jalf Nov 29 '11 at 13:34
  • "_you're sending two bytes into the stream instead of one_" you might want to clarify this: some people might understand, literally, that { NEWLINE NUL } is output instead of just NEWLINE. – curiousguy Nov 29 '11 at 13:37
  • I agree with that, of course the null isn't printed to the stream. My point is that the null still has to be created in memory, which implies that there is going to be an extremely minimal performance degradation. I just realised that I wrote my answer in an ambiguous manner. I believe that the entire cstring is passed into `operator<<()`, which will only print the '\n'. – Chris Parton Nov 29 '11 at 13:38
  • 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 '11 at 13:40
  • Good point. I'll admit defeat at that. My theory is moot regardless, since it was based on the passing of data by value, when it's not for obvious reasons (cstrings can't be passed by value... what was I thinking?). I originally thought you were denying that "\n" was 2 bytes wide, which was why I contested your downvote :) – Chris Parton Nov 29 '11 at 13:48
  • 2
    @jalf But still there is a cost for iterating over an array of chars until the `'\0'` is found. – Christian Rau Nov 29 '11 at 13:50
  • 1
    @ChristianRau: Yeah, but in the case of "\n" vs '\n' that cost would be very minimal. – Chris Parton Nov 29 '11 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"`. – Christian Rau Nov 29 '11 at 14:00
  • True about `'\n'` vs `"\n"`. I was thinking of `"\n"` compared to `std::endl`. – jalf Nov 29 '11 at 14:02
  • It's been an interesting discussion at any rate. The main issue with my answer was that it was poorly worded. I thought about the cost of seeking the null character, but @jalf trumped my main argument with the static storage remark. Rookie mistake on my part haha. – Chris Parton Nov 29 '11 at 14:12
  • "you're sending a char* to operator<<() (usually 4 bytes on a 32-bit system) as opposed to a single byte for a char." This still isn't quite right, since a 32 bit calling convention is, I think, unlikely to pass a `char` argument in less than 4 bytes of register or stack. It's just that 3 of them will be either zeroed by the caller, sign-extended by the caller, or ignored by the callee. As you say, borderline irrelevant :-) – Steve Jessop Nov 29 '11 at 15:27
  • Yeah, that is wrong. I edited my post, made it italic and wrote "This is wrong," but I think @ChristianRau was editing the post at nearly the same time and it overwrote my changes. Ay any rate, the `char` is passed by reference, so my point is irrelevant haha. I'll re-edit the post. Edit: My bad, the text saying that it was wrong is still there, just not the italics. – Chris Parton Nov 29 '11 at 22:21
  • @Chris Sorry for the edit, but I thought the italics were a typo, since they used the `*` from `char*` and this ended up as a simple `char` which was just wrong. – Christian Rau Nov 29 '11 at 23:37
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).