Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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.

like image 460
fewu Avatar asked Nov 26 '13 07:11

fewu


People also ask

Why we use the exit () method in C?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. void exit (int code); The value of the code is returned to the calling process, which is done by an operation system.

Can we use exit in C?

Exit() is a core function in the C/C++ programming language that is used to instantly end the calling process (function). It is possible to call from any function. It informs the operating system of the state of program termination by passing an int value. It is usually used when software crashes unexpectedly.

How do you exit a C++ program in terminal?

exit functionh>, terminates a C++ program. The value supplied as an argument to exit is returned to the operating system as the program's return code or exit code. By convention, a return code of zero means that the program completed successfully.


1 Answers

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.

like image 144
masoud Avatar answered Nov 08 '22 02:11

masoud