Is there any difference between return n
(in the main
function) and exit(n)
in C? Is it defined by C or POSIX standards or it depends on OS or compiler?
Difference Between return n and exit(n) in C
cstandards
cstandards
Is there any difference between return n
(in the main
function) and exit(n)
in C? Is it defined by C or POSIX standards or it depends on OS or compiler?
Best Answer
In most cases, there's no difference, but here's a C program that's likely to behave differently depending on whether it uses
return 0;
orexit(0);
:Because of the
atexit()
call, eitherexit(0);
orreturn 0;
causes thecleanup
function to be invoked. The difference is that if the program callsexit(0);
, the cleanup happens while the "call" tomain()
is still active, so thelocal_message
object still exists. Executingreturn 0;
, however, immediately terminates the invocation ofmain()
and then invokes thecleanup()
function. Sincecleanup()
refers (via the globalmessage
pointer) to an object that's allocated locally tomain
, and that object no longer exists, the behavior is undefined.Here's the behavior I see on my system:
Running the program without
-DUSE_EXIT
could do anything, including crashing or printing"hello, world"
(if the memory used bylocal_message
happens not to be clobbered).In practice, though, this difference only shows up if objects defined locally inside
main()
are made visible outsidemain()
by saving pointers to them. This could plausibly happen forargv
. (Experiment on my system shows that the objects pointed to byargv
and by*argv
continue to exist after returning frommain()
, but you shouldn't depend on that.)