Back to results for “I/O Streams”
C++ › I/O Streams

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

Intermediate

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.

Common follow-ups: What extra work does std::endl do? | When is flushing needed?