I've tried to read up on the difference between return EXIT_SUCCESS;
from main()
and calling exit(EXIT_SUCCESS)
from anywhere, and the best resource I've found so far is this answer here on SO. However, there is one detail I'd like to have cleared up.
To me, the most compelling argument against exit()
(as laid forward in that post) is that no destructor is called on locally scoped objects. But what does this mean to other objects? What if I'm calling exit()
from somewhere else, quite far away on the stack from the main()
method, but in block (even a method) that contains only that call, and no variables? Will objects elsewhere on the stack still be destructed?
My use case is this:
I have an application that keeps prompting the user for input until the "quit" command is given (a text-based adventure game). The easiest way to accomplish that, was to map "quit" to a method that simply calls exit(EXIT_SUCCESS)
. Of course, I could write it so that every action the user can take returns a boolean indicating wether the game should go on or not, and then just return false
when I want to quit - but the only time I'd return anything but true
is from this method - every other action method would then have to return true
just because I wanted to avoid exit()
. On the other hand, I create quite a lot of objects and allocate quite a lot of memory dynamically - all of that has to be taken care of by class destructors, so it is crucial that they do run.
What is best practice here? Is this a good case for exit()
, or just as bad as in the main
method?