Is there any difference between return 0
and exit (0)
when using in a function? If yes, When should I use return 0
or exit (0)
in a function?
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. Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.
return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used.
When you write return you are actually returning void value and you are simply returning 0 when you write return 0. So, you generally use return 0 when return type is int and return when return type is void.
In your case,since return 0 is placed in main ,the program will exit. return will terminate the execution of the function and returns control to the calling function. When it is placed in main , it will exit the program. In order for main to return an int , use int main instead of void main .
return
exits from the function while exit
exits from the program.
In main
function executing return 0;
statement or calling exit(0)
function will call the registered atexit
handlers and will cause program termination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With