How to exit a program with mixed C / C ++

I am interacting with a C program ( main() located in C) with C ++. In some cases, in my code, I want to stop the program. Now I would like to know how can I do this cleanly?

At the moment, I call std::terminate() , but more because of a lack of better ideas. The main thing that bothers me, is not that I do not free up memory (because it is freed from program termination anyway, right?), But the MSVS Just-in-time Debugger pops up and I get an ugly error message ending time execution in an unusual way.

EDIT: since this caused confusion: returning to main() with return 0 is not possible in this case.

+7
c ++ c
source share
2 answers

If you are worried about cleaning up and calling destructors, then

 exit(EXIT_SUCCESS); // or EXIT_FAILURE 

is the best choice between exit , terminate and abort .

  • The exit function calls the descriptors and clears the objects of automatic storage (an object declared in the global scope). It also calls the functions passed to atexit .

  • The abort function is useful for abnormal exits and does not clear anything. It does not call functions passed to atexit .

  • The terminate function does not exist in C. It is useful when you have an exception and you cannot handle it, but you end the program.

+7
source share

main The function starts there, the main function is where it should end normally. If you use return 0; , this indicates a successful exit.

 int main(void) { //init //do stuff //deinit return 0; // bye bye } 

You can also use exit(0); but if your exit points are scattered everywhere, this makes debugging difficult.

+3
source share

All Articles