c++buffercoutflushendl

seeking clarity regarding std::cout and std::endl


I am trying to get a better understanding of what happens to the buffer when we do not use std::endl after std::cout.

Let us consider the following piece of C++ code -

int main(int argc, char** argv) {

    std::cout << "Hello World!";
    return 0;
}   

As per my understanding, std::cout would add the string Hello World! to the buffer. If we do not add std::endl at the end of the code - std::cout << "Hello World!" << std::endl; , should we or should we not expect Hello World! to be printed as output?


Solution

  • Yes, since all streams are flushed at their destructors, and global std::cout object will be destructed upon program exit, the string will be printed.

    Note, however, that there will be no new line character in the end of the printed string, so console prompt would look unusual (and ugly) with your regular prompt immediately following Hello World!.