What is difference between return and exit statement in C Programming
- return is an instruction of the language that returns from a function call.
- exit is a system call (not a language statement) that terminates the current process.
The only case when both do the same thing is in the main()
function, as a return from main performs an exit()
.
Example with return
:
#include <stdio.h>
void f(){
printf("Executing f\n");
return;
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f Back from f
Another example for exit()
:
#include <stdio.h>
#include <stdlib.h>
void f(){
printf("Executing f\n");
exit(0);
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f
You never get "Back from f". Also notice the #include <stdlib.h>
necessary to call the library function exit()
.
Also notice that the parameter of exit()
is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).
The parameter of the return statement is whatever the return type of the function is. If the the function returns void, you can omit the return at the end of the function.
Last point, exit()
come in two flavors _exit()
and exit()
. The difference between the forms is that exit()
calls functions registered using atexit()
or on_exit()
before really terminating the process while _exit()
(from #include <unistd.h>
, or its synonymous _Exit from #include <stdlib.h>
) terminates the process immediately.
In C, there's not much difference when used in the startup function of the program (which can be main()
, wmain()
, _tmain()
or the default name used by your compiler).
If you return
in main()
, control goes back to the _start()
function in the C library which originally started your program, which then calls exit()
anyways. So it really doesn't matter which one you use.