简体   繁体   中英

Isn't std::endl redundant?

Flush happens in the following cases:

  • std::cerr
  • std::cin
  • program termination
  • in many implementations, standard output is line-buffered, meaning "\\n" flushes anyway

So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.

std::cerr

But what if I do not want to write to stderr, but rather stdout?

std::cin

But what if I just want to give the user some status update and do not want any input?

program termination

As above, what if I want to tell the user something before the program is done?

in many implementations, standard output is line-buffered, meaning "\\n" flushes anyway

But what about the platforms that don't? Regardless of whether or not such a platform currently exists, I want my code to work as intended as defined by the standard, not as by "meh, will probably be fine on all implementations".

If all of the above apply (the fourth point actually always applies), you need to flush "by hand". If the flush gets handled by one of the first three, you don't.

So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.

No it's not redundant , since implementation of flushing along '\\n' isn't mandated by the standard. That's just an implementation specific behavior, while the behavior of std::endl is always clearly defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM