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?
相关问题
- Multiple sockets for clients to connect to
- Keeping track of variable instances
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- glDrawElements only draws half a quad
return
is a statement that returns control back to the calling function.exit
is a system call which terminates the current process i.e the currently executing program.In
main()
thereturn 0;
andexit(0);
perform the same thing.NOTE: you have to include
#include<stdlib.h>
.return
exits from the function whileexit
exits from the program.In
main
function executingreturn 0;
statement or callingexit(0)
function will call the registeredatexit
handlers and will cause program termination.Yes there is, since there is no statement called
exit
. I guess you mean the functionexit
?In that case, there is a big difference: The
exit
function exits the process, in other words the program is terminated. Thereturn
statement simply return from the current function.They are only similar if used in the
main
function.exit 0
is a syntax error in C. You can haveexit(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. Thereturn
statement instead only quits the current function giving the caller the specified result.They are the same only when used in
main
(because quitting themain
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:In this case if function
a
calls functionb
that calls functionc
that callssafe_malloc
you may want to quit the program on the spot instead of returning toc
an error code (e.g. aNULL
pointer) if the code is not written to handle allocation failures.