tags:

views:

145

answers:

2

What is difference between return and exit statement in C Programming

+18  A: 
  • 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.

kriss
thanks for ur answer it's really good
shona
exit() is not a system call
anon
@anon: you are right, technically it's a return to system, but there is not much difference.
kriss
+1  A: 

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.

Dumb Guy
It does matter. exit() immediately terminates the program, no matter where it is called. return only exits the current function. the only location they do the same thing is in main()
yodaj007
Thanks, i have fixed the wording. It is not necessarily only in main(), as not all compilers use the same function name for the startup function.
Dumb Guy
I guess you write all your programs in one big main function? ;-)
C Johnson