Reputation: 229
I'm interfacing a C program (main()
is in C) with C++. At some points in my code I want to stop execution of the program. Now I'd like to know, how can I do this cleanly?
At the moment I call std::terminate()
but more out of a lack of better ideas. The main thing that bugs me isn't even that I'm not freeing the memory (because it's freed anyway on program termination, right?) but that the MSVS Just-in-time Debugger pops up and I get an ugly error message about terminating the runtime in an unusual way.
EDIT: As this has caused confusion: Returning from main()
with return 0
is not possible in this case.
Upvotes: 7
Views: 2067
Reputation: 56479
If you concern about cleaning up and invoking destuctors then
exit(EXIT_SUCCESS); // or EXIT_FAILURE
is the best choice between exit
, terminate
and abort
.
Function exit
calls descructors and cleans up the automatic storage objects (The object which declared in the global scope). It also calls the functions passed to atexit
.
Function abort
is useful for abnormal exits and will not clean up anything. It doesn't call the functions passed to atexit
.
Function terminate
does not exist in C. It's useful when you have an exception and you can't handle it but finishing the program.
Upvotes: 7
Reputation: 16043
main
function is where it starts, main
function is where it should end usually. If you use return 0;
it indicates succesful exit.
int main(void) {
//init
//do stuff
//deinit
return 0; // bye bye
}
You could also use exit(0);
, but if your exit points are scattered all over the place it makes things harder to debug.
Upvotes: 3