Advertisement
Intermediate C++, I/O Streams

What is the difference between std::endl and '\n'?

Short answer

'\n' inserts a newline character. std::endl inserts a newline AND flushes the stream's buffer. Flushing forces output immediately but is comparatively expensive; overusing std::endl in loops hurts performance.

Save C++ mock interview
Advertisement
AModel answer
'\n' inserts a newline character. std::endl inserts a newline AND flushes the stream's buffer. Flushing forces output immediately but is comparatively expensive; overusing std::endl in loops hurts performance. Prefer '\n' for normal output and reserve std::endl (or std::flush) for when you truly need an immediate flush.
std::cout << "line\n";     // fast
std::cout << "line" << std::endl; // newline + flush (slower)
Real-world example
Replacing std::endl with '\n' in a tight logging loop noticeably speeds up output.
Likely follow-ups
  • What extra work does std::endl do? | When is flushing needed?
Related topics