-2

I am reading the following example from wikipedia.

#include <iostream>

int main()
{
    std::cout << "Hello, world!\n";
    return 0;
}

The article reads then as:

This program would output "Hello, world!" followed by a newline and standard output stream buffer flush.

I do not believe this is correct, since a std::flush is not required on '\n'.

Should I go ahead and edit the article changing the '\n' into std::endl ?

malat
  • 12,152
  • 13
  • 89
  • 158
  • apparently, on a question of the type "is X true", downvotes are no longer used to say 'bad question', but to say 'no' – sp2danny Jan 27 '15 at 15:45
  • I think @sp2danny was being a bit sarcastic. Downvotes *shouldn't* be used to indicate that the answer is "no". (But we don't know the reason for the downvote.) – Keith Thompson Jan 27 '15 at 17:17

2 Answers2

4

No, standard output is flushed when the program terminates normally. (If a simple "Hello, world" program terminates abnormally, there's probably not much you can do about it.) You might want to clarify that point, though (that the flush happens at the end of the program, not on the std::cout << ... call).

And the return 0; is unnecessary (but harmless).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 1
    I believe you need to reword `program terminates`, I believe flushing only occur when no abnormal program termination occur (abort...). – malat Jan 27 '15 at 15:48
2

By default, the cout stream is synchronized with the C library's stdout stream (i.e. they will share the same buffer). And the C standard specifies that stdout will be line-buffered or unbuffered when writing to an interactive device.

What this means is that by default, cout will flush when printing \n if the output is an interactive device such as a console. If you call std::cout.sync_with_stdio(false), it may not flush anymore.

Additionally to this, the output will be flushed at program termination as the other answer says.

interjay
  • 107,303
  • 21
  • 270
  • 254