Search code examples
cerror-handlingterminate

In C, can a function exit() or should it allow main() to handle that?


I'm writing a C program, and I'm curious about something. The program has several functions that return 1 on success and 0 on failure, and most are called by main() (though some are called by other functions). This is for an assignment, and if an error is caught I need to print the error to stderr using fprintf() and terminate the program.

What is the proper way to handle error termination? Should I allow the function to print to stderr, then return 1 back to main() then have main() actually terminate, or should the function itself handle error printing and program termination?


Solution

  • The C standard states:

    5.1.2.2.3 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument.

    So it is perfectly valid, when you encounter a fatal error to do a exit(errcode);

    Usueful to know: with atexit() you can specify a function (with no argument) that will be called by exit() (for example to clean up the mess). You can even define several such functions: they will be called in the reverse order of their registration.