10

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Umal Stack
  • 241
  • 4
  • 7
  • That's not at all the same question as the one cited above. He's apparently familiar with the answers to the cited question (`exit` doesn't call local destructors. He's asking why. – James Kanze Apr 11 '13 at 09:57
  • @JamesKanze Ok. We have been a little too quick on this one. Voting to reopen the question, removed downvote. – Jean Apr 11 '13 at 09:58
  • Even though the accepted answer in the linked-to question gives a hint ("exit() does not return") to the reason, I agree that it is certainly not a duplicate. It's an entirely different question. – Damon Apr 11 '13 at 10:11

1 Answers1

8

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329