开发者

Why is explicitly returning 0 from main() considered good practice? [duplicate]

This questi开发者_StackOverflow中文版on already has answers here: Closed 12 years ago.

Possible Duplicate:

return statement vs exit() in main()

I've just read the first chapter of Accelerated C++ (seems like an awesome book), and at the end the author says

However, explicitly including a return from main is good practice.`

Why is this considered good practice? In C99, I always omitted the return 0, using exit() to signal abnormal program termination, and never missed the explicit return.


A couple of reasons,

firstly, main is declared to return int, and so it should

secondly, and maybe more importantly for C++ an exit() from main will skip calling destructors for local object instances in main.


In C99 and in C++ if execution of the program reaches the closing brace of the main() function then an implicit return 0; is executed. That wasn't the case in C90 - reaching the end of main() without an explicit return would result in an indeterminate value being returned (strictly speaking, the behavior is undefined).

I can only guess that the authors of "Accelerated C++" feel that the explicit return is good practice simply because it makes your intent explicit. The only other reason I can think of is that it makes code compatible with C90, but I find it difficult to believe that that would hold much weight as a reason.


The calling program (usually a OS shell) can gather the return code and know if the program failed or not.

Having a single exit point from a program makes a good place to put a breakpoint.

Having a single execution flow makes it easier to follow a program if you're unfamiliar with it.


I think this rule of thumb not so much applies to callling exit() instead, but to fall off main() without returning anything, relying on the implicit return 0 the run-time system has to do in that case.

I guess that main() is the only function returning a value where you can omit explicitly returning a value. IMO that's a very good reason to not to rely on that rule.


By C++ standard main() should return int. This is an error code application returns on its termination and in practice this is useful when calling process wants to know whether this application terminated with success (usually error code is 0 in this case) or it failed.

I'll give a Microsoft specific example, but it shows general need for returning error code: ProcessA needs to create ProcessB and wait for it to terminate, after which it wants to check whether ProcessB executed successfully. ProcessA will use CreateProcess function to create ProcessB, then will use ProcessB's handle to wait for its termination and then will use GetExitCodeProcess function to get ProcessB termination code - which is int value returned from main().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜