Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit(0) vs return 0

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.Note that static objects will be cleaned up even if we call exit().

There should be some reason behind this logic. i just want to know what it is? Thank you.

like image 305
Umal Stack Avatar asked Apr 11 '13 09:04

Umal Stack


1 Answers

In the case of exit( 0 ), you're calling a function. You don't expect the destructors of local variables to be called if you're calling a function. And the compiler doesn't know, a priori, that there is anything special about exit( 0 ).

In fact, this rationale really only applies to C++ before exceptions. The standard could redefine exit() to throw an implementation defined exception with the argument, and specify that the call to main is wrapped in a try block which catches this exception, and passes the return code back to the system. This would mean that exit have a completely different semantics in C and in C++, however; at any rate, there's been no proposal before the committee to make this change.

like image 130
James Kanze Avatar answered Oct 03 '22 08:10

James Kanze