So exit() exits completely out of the program, is there any better way ? |
Almost certainly, yes. If you must quit and for whatever reason you cannot reliably reach main to return normally,
throw an exception.
exit()
introduces a hidden control path which terminates your program without destroying objects with automatic storage duration. This means that all of the resources you own in an automatic context (i.e., most of them) will simply leak, no matter what you do. More importantly, if your destructors do real work, they will simply be skipped, and code that you could otherwise guarantee would run wouldn't.
If you need to just transfer control elsewhere (give up) and simply returning is not feasible, then throw and optionally catch an exception. The stack unwinding that takes place as result of an exception (almost*) guarantees the destruction of automatic objects.
exit()
makes more sense in the context of C programs, especially in combination with careful use of
atexit()
to release resources. Such a C++ program would be very unidiomatic in most (but not all) cases.
*almost, because the destructor can technically throw too. Throwing from a destructor is usually a bad idea.