From within the main
function, exit(N)
and return N;
are very nearly identical (but see below).
exit()
terminates the entire execution of the program. return
merely returns from the current function. (I know you said you know the difference, but I want to be complete).
If you're in main
, you can use either one you like. The choice is a matter of style, and I don't think there's any agreement on what style is the best. You might consider using exit
in case the code in main
is later moved into some other function. I'd use return
from main
for more normal program termination.
Note that the value either passed to exit
or used by return
has a somewhat system-specific meaning. The value is returned to the calling environment. 0
or EXIT_SUCCESS
denotes success; EXIT_FAILURE
denotes failure. (EXIT_SUCCESS
and EXIT_FAILURE
are macros defined in <stdlib.h>
, the same header that defines the exit
function).
Any other value will have a system-specific meaning. In particular, there have been systems (VMS in particular) on which exit(1)
indicates success, not failure. On a Unix-like system, where 1
denotes failure, EXIT_FAILURE
will be defined as 1.
You can use EXIT_SUCCESS
and EXIT_FAILURE
with either return
or exit()
.
On the other hand, if you need to specify more than one kind of failure, EXIT_FAILURE
won't be enough. On Unix-like systems, and probably on Windows, 0
denotes success, 1
denotes a more or less generic failure, and other small positive integers denote other kinds of failure. Feel free to use specific values if that's what you need; you probably don't care that your program may not work as expected on VMS. (I'd define constants for the various exit values you use, and clearly say what they all mean in the documentation.) Again, you can use either exit()
or return
, whichever is more convenient.
I said above that exit(N)
and return N
from main()
are almost identical.
It's legal in C for main
to call itself recursively. If your program is in main
, but not in the initial invocation of main
, then return
will terminate the current execution of main
, but will not terminate the program; it's just like return
vs. exit()
for any function other than main
. Calling main
recursively is almost always a bad idea, so this is worth being aware of, but not worth worrying about.
Also, atexit()
can be used to register functions to be called automatically on program exit. Any such functions will be called whether the function terminates due to exit()
or return
. The difference (and it's an incredibly obscure one) is that exit()
is called by main
, and return
immediately leaves main
. So if one of your atexit()
-registered functions refers to a local variable inside main
, that variable will still exist if you called exit()
, but not if you executed a return
statement. You would have to go out of your way to make this happen, and there's no good reason to do so, so you almost certainly don't have to worry about this particular issue.