1

I'm new to C++ and as far as I know that using escape sequence '\n' will not flush the output buffer (as it happens when using endl), but in my case when debugging the following program using F11 (step into) under qt-creator on Ubuntu 14.04, the output of the function (which is 5) is directly being printed to the console.

#include <iostream>

void printValue(int nValue)
{
    std::cout << nValue << '\n';
}

int main()
{
    using namespace std;
    printValue(5);
    return 0;
}

When I removed the '\n' from the output in line no. 5, the output postponed till the end of the execution.

  • Why is this?
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
GeoLinux
  • 21
  • 4
  • See the libc functions: setbuf and setlinebuf. setlinebuf is the implicit default for stdout/stderr [aka std::cout/std::cerr] for programs when they start up. For streams you open yourself, they're given a default buffer size and the buffer must fill before it's flushed. – Craig Estey Oct 02 '15 at 18:44

3 Answers3

3

Yes, endl will cause a flush, but that doesn't mean the buffer can't decide to flush itself for other reasons. See this reference, particularly this:

In many implementations, standard output is line-buffered, and writing '\n' causes a flush anyway

djs
  • 1,660
  • 1
  • 17
  • 35
2

The time of flushing is not defined by the standard, so the stream can flush at any time.

Daniel
  • 30,896
  • 18
  • 85
  • 139
0

It's actually implementation dependent, if '\n' seen in the std::ostream triggers flushing.

The enforced and safe method is to use std::endl.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190