Is there a guarantee of stdout auto-flush before exit? How does it work?

余生颓废 提交于 2019-12-01 15:33:08

This is accomplished by these two sections in the C++ language specification:

[basic.start.main]

A return statement in main has the effect of leaving the main function and calling exit with the return value as the argument.

and

[lib.support.start.term]

The function exit has additional behavior in this International Standard:

  • ...
  • Next, all open C streams with unwritten buffered data are flushed.
  • ...
Eric Postpischil

Generally, a return from main is not the end of your program, nor is entry to main the start.

Usually, the linker that creates the final executable for your program marks some location, perhaps named start, as the place where execution is to begin. When the operating system loads your program and starts executing it, it starts execution at this place. There is code there that sets up an environment: Creates a stack, sets stream states, et cetera. Then this code calls main.

When main returns, it returns to this special code. That code then performs various clean-up work that is required at the end of a C or C++ program, as described in this answer.

If a program is terminated abruptly, this final code might not be executed.

When main() exits, all open streams are closed... to include stdout. Closing the open stream flushes stdout and what you've written to the buffer gets committed with or without the newline.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!