exit 0
is a syntax error in C. You can have exit(0)
that is instead a call to a standard library function.
The function exit
will quit the whole program, returning the provided exit code to the OS. The return
statement instead only quits the current function giving the caller the specified result.
They are the same only when used in main
(because quitting the main
function will terminate the program).
Normally exit
is only used in emergency cases where you want to terminate the program because there's no sensible way to continue execution. For example:
//
// Ensure allocation of `size` bytes (will never return
// a NULL pointer to the caller).
//
// Too good to be true? Here's the catch: in case of memory
// exhaustion the function will not return **at all** :-)
//
void *safe_malloc(int size) {
void *p = malloc(size);
if (!p) {
fprintf(stderr, "Out of memory: quitting\n");
exit(1);
}
return p;
}
In this case if function a
calls function b
that calls function c
that calls safe_malloc
you may want to quit the program on the spot instead of returning to c
an error code (e.g. a NULL
pointer) if the code is not written to handle allocation failures.