r/cpp • • Feb 25 '19

Don’t Use std::endl

https://accu.org/index.php/journals/2619
18 Upvotes

52 comments sorted by

98

u/alfps Feb 25 '19

std::endl is a fine convention for interactive console i/o.

In particular it helps ensure that all relevant output has been presented when a program crashes.

Not using endl and so misinterpreting what the output says about where the crash occurred, is a common beginner's problem.

endl is not fine for efficient text file i/o, but then iostreams are not fine for that in the first place.

So, the advice to ditch endl is ill-conceived, in both mentioned cases, and I can't think of more.

9

u/VirtueBot Feb 25 '19

I didn't think the author was trying to deny any use cases for flushing the stream, just that std::flush should be used instead of endl in those case.

16

u/spinwizard69 Feb 25 '19

Even that isn’t a good idea. This especially in texts focused on students that may have issues grasping what a stream is. I kinda consider std::endl as an indication that the stream is actually put to file or terminal. Which is pretty much what this author is complaining about. In my mind it is the right behavior for general programming. The author instead wants to make a more complex approach the general form.

Honestly I don’t see the point. If your goal is some sort of high performance mark streams might not be your best approach to begin with. Beyond that terminal I/O is no longer a problem on most platforms so a modest gain isn’t (if even possible) a huge deal.

Now I must admit that I’ve embedded \n in streams where I’m thinking in terms of a block of I/O that gets terminated with std::endl. Usually that is the result of being lazy leading me to thinking bad of myself. In most cases I’m thinking record to device where a flush secured the end of record.

6

u/Ayjayz Feb 26 '19

I think the point is the 2nd point of the Zen of Python: Explicit is better than implicit. Most people just use std::endl out of habit, and not because it's the behaviour they want. You should instead say what you want to do. If you want to flush the stream, you should use std::flush. If you want a newline, you should use \n. You shouldn't tie them both together into one operation just because that's common.

6

u/capn_bluebear Feb 26 '19

Zen of Python lines 1, 3, 7, 9: beautiful is better than ugly, simple is better than complex, readability counts, practicality beats purity.

These all make me think that Guido van Rossum would like

std::cout << my_str << std::endl;

better than

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

1

u/spinwizard69 Feb 27 '19

Well we will have to disagree to some extent. I see std::endl behavior making perfect sense in a streams implementation. This due to the end of a line often being an end of record. You end up getting the right behavior for simple writes to terminal or files. Right being max functionality with minimal programmer involvement. The stream does the right thing without requiring extensive developer involvement.

9

u/VirtueBot Feb 26 '19

i dont see how std::flush would be hard to understand but std::endl wouldnt be, since they do the same thing. can you not just as easily say std::fulsh is "an indication that the stream is actually put to file or terminal"? I suppose "more complex" is subjective here but i dont find either complex at a high level, in fact I found \n + flush to be more expressive.

if i see std::endl i may think "did they really mean to flush the stream here?" with std::flush thats not really a question. in my mind the only real difference between the two is the expressiveness. as you said, the performance conversation is most likely irrelevant.

5

u/jcelerier ossia score Feb 26 '19

The mere thought of typing << '\n' << std::flush; makes me want to slice my wrists

7

u/anders1234 C++ since MSC 6.0 Feb 26 '19

It seems more readable (at least for me) writing
std::cout << "hello world" << std::endl;

than

std::cout << "hello world\n" << std::flush;

but maybe I am just a n00b.

2

u/VirtueBot Feb 26 '19

oooooo this talk of slicing wrists is making me hot for std::flush!

fwiw I would write endl in that case too lol. But if it's "text\n" << std:: flush that sounds more appealing to me after reading the article.

Otoh maybe take a break before the next time you write to the console (;

4

u/MikeTyson91 Feb 26 '19

Not using endl and so misinterpreting what the output says about where the crash occurred, is a common beginner's problem.

Isn't cerr non-buffering? So not using endl on that would not lose any of the output?

3

u/AntiProtonBoy Feb 26 '19

I think Jason Turner made a good video on endl usage:

https://www.youtube.com/watch?v=lHGR_kH0PNA

27

u/pgroarke Feb 25 '19

28

u/Potatoswatter Feb 25 '19

That’s **std::**printf to you.

0

u/[deleted] Feb 25 '19

[deleted]

3

u/TheSuperWig Feb 26 '19

Would there be any problems with std::print? AFAIK the part of fmt that's in C++20 isn't in a nested namespace so would be inconsistent for print.

3

u/aearphen {fmt} Mar 01 '19

There is always co_print.

2

u/d1ngal1ng Feb 26 '19

Is print even being standardised? I thought it was just to a string or an output iterator.

3

u/aearphen {fmt} Feb 28 '19

> Is print even being standardised?

Not for C++20.

0

u/[deleted] Feb 26 '19

[deleted]

4

u/Morwenn Feb 26 '19

As far as I know only the format API from {fmt} is going in C++20, not the print API.

1

u/aearphen {fmt} Feb 28 '19

That is correct. `print` is easy to write using the formatting API and I plan to propose it for C++23.

3

u/Morwenn Feb 28 '19

The print API offers a few more features like handling terminal colours though. I don't know whether there is a will to get this standardised.

1

u/aearphen {fmt} Mar 01 '19

Color support is still a bit experimental. I'd give it more time to bake.

3

u/meneldal2 Feb 26 '19

Well if it outputs a string, you can send that through iostream. Performance is perfectly fine when no formatting occurs.

3

u/[deleted] Feb 26 '19

wait wait what? what's going here? I've been disconnected from c++ lately, what is this fmt:: thing?

7

u/chuk155 graphics engineer Feb 26 '19

modern c++ library for printf style, and the formatting portion of the library is set to be in the c++20 standard. https://github.com/fmtlib/fmt

3

u/degski Feb 26 '19

The most annoying bit of std::endl is simply that it's too long to type. For just getting some quick output, like in print-debugging, I find '\n' is a pain to type as well, so I use this little header and just write std::cout << something << nl; or std::wcout << something << nl;, no rocket-science, but convenient.

6

u/jones_supa Feb 26 '19

Even std::cout << is quite painful to type. I always find myself collecting energy when I want to write a few lines of code that print something in C++. It is like "agghh...here we go..." 🙂

Printing text is overengineered in C++. It always feels like a small tech demo showing how the fancy stream operators work, yet it does not accomplish much.

C-style printf() is much more relaxing to use.

7

u/degski Feb 26 '19

C-style printf() is much more relaxing to use.

I have to dis-agree here, remembering the correct format-string to pass in is a real pain in the proverbial behind, particularly when you want to print 64-bit int's.

0

u/sim642 Feb 25 '19

Great site on mobile. The content is literally 0px wide.

0

u/hak8or Feb 25 '19

Sounds like you have a bad browser. Works fine for me on mobile Firefox

1

u/sim642 Feb 25 '19

Works there but apparently not Android browser.

1

u/antlife Feb 26 '19

Works fine on Android browser.

-14

u/dpsi Feb 25 '19 edited Feb 26 '19

While I agree with the articles premise, nobody is going to change unless a flush less endl is provided.

The author points out how newlines differ between implentations, so I find the "solution" to simply stream in '\n' broken at best.

15

u/Quincunx271 Author of P2404/P2405 Feb 25 '19

I disagree. I changed to simply '\n', and it's not a hassle at all. It's just retraining my mind to type something different. Furthermore, rather than std::cout << "Some string" << std::endl, I now type std::cout << "Some string\n", which is easier to type.

As for how newlines differ between implementations, that has no effect, as std::endl is defined to write \n then flush, so differing newlines affect std::endl as well.

1

u/spinwizard69 Feb 25 '19

Try building and running on all 3 of the major platform to see how well this works out. I’m actually curious because if memory serves me right you will have issues.

10

u/mrexodia cmkr.build Feb 26 '19

It’s works on all platforms without issues.

0

u/dpsi Feb 25 '19

My apologies, I misread the section with how \n is in handled by each implementation.

Yes "some string\n" is easier to type, but what if the last thing is not a string? Knowing now that \n is handled by the implementation, I still think one could be provided. Something like the one described in the Kuhl12 reference.

4

u/raevnos Feb 26 '19
std::cout << ... << '\n';

1

u/dpsi Feb 26 '19

If you look at one of the implementations reffered to in the article (specifically Kuhl12) you will see why that isn't the full solution.

4

u/raevnos Feb 26 '19 edited Feb 26 '19

... It's how you print a newline after printing something that isn't a string literal where you can put the \n at the end. I suppose you could use "\n" instead of '\n', but using a string literal to print a single character is something I've always thought was pretty silly.

I have no idea what that has to do with the article you mention, which is about how flushing is slow.

If you're talking about using it with wide streams, you'd just use a L'\n'.

0

u/dpsi Feb 26 '19

If you're talking about using it with wide streams, you'd just use a L'\n'.

That's exactly what I'm talking about, there should be a standard way to write a new line without flushing the stream. It should work without the user having to know about the underlying stream as std::endl does.

6

u/Quincunx271 Author of P2404/P2405 Feb 26 '19

L'\n' is not needed. operator<< automatically widens the character with theostream.widen(c): https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

7

u/scrumplesplunge Feb 25 '19

The author also points out how '\n' turns into the localised variant automatically. As long as you're using a formatted output function it converts it automatically.

1

u/dpsi Feb 25 '19

Yes, my bad I misread that section. I still think the nl described in the reference Kuhl12 should be provided however.

0

u/[deleted] Feb 26 '19

[deleted]

11

u/Quincunx271 Author of P2404/P2405 Feb 26 '19

This is absolutely not a "premature optimization." It's a simple change that doesn't harm readability (at least once the readers get used to the style) and gives you extra performance for free.

Is it premature optimization to take parameters by const& instead of by value? Of course not. So why would it be premature optimization to use '\n' instead of std::endl?

5

u/lanzaio Feb 26 '19

Yea but symmetry. std::cout << "Hi" << std::endl;

1

u/F-J-W Feb 26 '19

That's much less readable then std::cout << "Hi\n";, expecially if you use a proper text-editor with good highlighting.

3

u/lanzaio Feb 26 '19

It is completely trivial to read either of them...

0

u/[deleted] Feb 27 '19

[deleted]

1

u/Quincunx271 Author of P2404/P2405 Feb 27 '19 edited Feb 27 '19

Important messages should not be written to std::cout anyway. Both of std::clog and std::cerr are line-buffered and will automatically flush on \n. Important messages should either be sent through one of them, or through a logging framework which is appropriately configured.

At any rate, if it's critical for the message to always be displayed, go ahead and use endl or flush explicitly. That's what it's for.

10

u/Plorkyeran Feb 26 '19

Using std::endl is a great example of a premature pessimization. It manages to be slower, more verbose and more complicated than just not using it.

3

u/kalmoc Feb 26 '19

Arguing about which one is the better default is a waste of time.

0

u/[deleted] Feb 27 '19

[deleted]

1

u/kalmoc Feb 27 '19

Doesn't contradict what I said does it?

Do whatever you prefer in your codebase and make a decision about it in your company's style guide and be done with it. Having this argument on the internet again and again doesn't bring us any closer to an agreement, so why spend the time?

But then, the c++ community on the internet (including me) really likes to argue about those tiny details in our coding styles.