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?
|
|
|
In most cases, there's no difference, but here's a C program that's likely to behave differently depending on whether it uses
Because of the Here's the behavior I see on my system:
Running the program without In practice, though, this difference only shows up if objects defined locally inside |
|||
|
|
When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used. Program 1 – - uses exit(0) to exit
Output: Inside Test’s Constructor Program 2 – uses return 0 to exit
Output:
Inside Test’s Constructor Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files. Note that static objects will be cleaned up even if we call exit(). For example, see following program.
Output:
Inside Test’s Constructor |
|||||||||||||||
|
|
Its worth noting that C standard (C99) defines two types of execution environments, Freestanding Environment and Hosted Environment. Freestanding environment is a C environment which does not support the C libraries and is intended for embedded applications and the like. A C environment which supports the C libraries is called a Hosted environment. C99 says, in a Freestanding environment program termination is implementation defined. So, if the implementation defines C99 defines Hosted environment behavior as,
|
|||||
|
|
From the C standard's perspective, not really, other than There are a couple of situations you want to watch out for:
The use of |
|||
|
|
