• Home
  • 2.6 Using std::endl

2.6 Using std::endl

View Categories

2.6 Using std::endl

< 1 min read

Table of Contents

The std::endl manipulator inserts a newline character into the output stream and immediately flushes the stream buffer. Flushing ensures that all buffered output is written to the destination before the program continues.

Although std::endl is convenient, it is generally used only when flushing the output stream is required. For ordinary line breaks, the newline character ('\n') is usually more efficient because it does not automatically flush the stream.

Source Code #

#include <iostream>

int main()
{
    std::cout << "First Line" << std::endl;
    std::cout << "Second Line" << std::endl;

    return 0;
}

Output #

First Line
Second Line

Explanation #

  • std::endl is a stream manipulator defined in the <iostream> library.
  • It inserts a newline character into the output stream.
  • After inserting the newline, std::endl flushes the output buffer immediately.
  • Flushing forces any buffered output to be written to the output device before the program continues.
  • Frequent use of std::endl may reduce performance because flushing the stream is relatively expensive.
  • When only a new line is needed, using '\n' is generally more efficient.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *