Search code examples
c++outputiomanip

What is in reality "endl" (or any output manipulator)? How is it implemented and how does it work with operator<<?


What is actually endl? Of course, it prints a new line and flushes the ostream buffer. But what is it actually? Can such "entities" like endl be defined by the programer?

There are these "output manipulators" which can be accessed using the library iomanip but what is actually going on when executing a command such as: cout << setprecision(5);

setprecision() looks like a function call, yet nothing is printed when using the cout instance. It changes the precision, but why simply not use the corresponding function member instead of adding more "abstraction" to code writing? By abstraction i mean non-intuitive code.

Thanks!


Solution

  • What is actually endl? Of course, it prints a new line and flushes the ostream buffer. But what is it actually?

    std::endl is a function. It

    Inserts a newline character into the output sequence os and flushes it


    Can such "entities" like endl be defined by the programer?

    Yes.

    Here's a demo program.

    #include <iostream>
    
    std::ostream& test_manip(std::ostream& out)
    {
       return (out << "In test_manip\n");
    }
    
    int main()
    {
       std::cout << test_manip;
    }
    
    

    and its output.

    In test_manip