What is the difference between exit and return?

Viewed 123883

What is difference between return and exit statement in C programming when called from anywhere in a C program?

5 Answers

For the most part, there is no difference in a C program between using return and calling exit() to terminate main().

The time when there is a difference is if you've created code that will be executed after you return from main() that relies on variables local to main(). One way that manifests itself is with setvbuf():

int main(void)
{
    char buffer[BUFSIZ];
    setvbuf(stdout, buffer, _IOFBF, BUFSIZ);
    …code using stdout…
    return 0;
}

In this example, the buffer provided via setvbuf() goes out of scope when main() returns, but the code that flushes and closes stdout will be attempting to use that buffer. This leads to undefined behaviour.

The other mechanism is to invoke atexit() with a function that accesses data from main() — via a pointer. This is harder to set up as the functions called via the atexit() mechanism are not given any arguments. So, you have to do something like this:

static void *at_exit_data = 0;

static void at_exit_handler(void)
{
    char *str = at_exit_data;
    printf("Exiting: %s\n", str);
}

int main(void);
{
    char buffer[] = "Message to be printed via functions registered with at_exit()";
    at_exit_data = buffer;
    at_exit(at_exit_handler);
    …processing…
    return 0;
}

Again, the buffer pointed at by at_exit_data has ceased to exist when the program returned from main() and so the handler function invokes undefined behaviour.

There is a related function, at_quick_exit(), but the functions registered with it are only called if the quick_exit() function is called, which precludes the functions being called after main() returns.

Related