C++: Difference Between \n and std::endl

In C++, both \n and std::endl are used to insert a newline in the output stream. However, there are important differences between the two that affect their behavior and performance.

\n: A newline character used to move the cursor to the next line in the output. It is lightweight and does not flush the output stream.

std::endl: A manipulator that inserts a newline and flushes the output stream. It is useful when you need to ensure that the output is immediately written to the console or file.

Flushing output stream means forcing the output buffer to immediately send its contents to the target destination (such as the console, a file, or another output device). Normally, the contents of the output buffer are sent automatically when the buffer becomes full, but flushing ensures that all data is written immediately, regardless of the buffer’s state.


Key Differences between Newline \n and std::endl

Aspect\nstd::endl
FunctionalityInserts a newline character into the output stream.Inserts a newline and flushes the output stream.
PerformanceFaster because it does not flush the stream.Slower due to the flushing operation.
Use CasePreferred for regular output when flushing is not required.Used when immediate flushing is necessary, such as in debugging.
SyntaxDirectly used as "\n".Used as std::endl.

Examples

Example 1: Using \n for Output

This example demonstrates how to use \n to print multiple lines of text.

</>
Copy
#include <iostream>

int main() {
    std::cout << "Line 1\n";
    std::cout << "Line 2\n";
    std::cout << "Line 3\n";
    return 0;
}

Output:

Line 1
Line 2
Line 3

Example 2: Using std::endl for Output

This example demonstrates how to use std::endl to achieve the same output but with flushing after each line.

</>
Copy
#include <iostream>

int main() {
    std::cout << "Line 1" << std::endl;
    std::cout << "Line 2" << std::endl;
    std::cout << "Line 3" << std::endl;
    return 0;
}

Output:

Line 1
Line 2
Line 3

When to Use \n and std::endl

  • Use \n for most situations where immediate flushing of the stream is not necessary, as it is more efficient.
  • Use std::endl when you need to ensure the output is flushed, such as when debugging or writing critical data to a file or stream.