</>EmbeddedInterview

What is the difference between exit() and return from main?

EasyC Programming

Short answer: In a hosted program, returning from main is equivalent to calling exit() with the returned value: functions registered with atexit() run, open FILE streams are flushed and closed, and temporary files are removed. _Exit() / _exit() terminate immediately without that cleanup. On a bare-metal microcontroller there is nobody to return to, so main should never return.

#include <stdio.h>
#include <stdlib.h>

static void cleanup(void) { puts("cleanup"); }

int main(void)
{
    atexit(cleanup);
    printf("work");          /* buffered */
    return 0;                /* or exit(0): flushes "work", prints "cleanup" */
    /* _exit(0) here would lose "work" (unflushed) and skip cleanup */
}

Differences that can matter

  • exit() can be called from any function; return only leaves main when written in main.
  • After return from main, main's local variables are gone before atexit handlers run, so a handler must not use pointers to them (for example, a setvbuf buffer that is a local array in main).
  • Exit status: EXIT_SUCCESS (0) and EXIT_FAILURE; only the low 8 bits reach the parent on POSIX.
  • In a multi-threaded program, exit() (or returning from main) ends all threads.
  • In a child process after a failed exec(), use _exit() so the child does not flush the parent's copied stdio buffers a second time.

Bare metal

  • The start-up code calls main() and, if it returns, typically falls into an infinite loop (b .) or calls exit(), which in newlib may loop forever or trigger a semihosting exit.
  • Firmware therefore ends with a super loop or starts the RTOS scheduler, which never returns:
int main(void)
{
    board_init();
    vTaskStartScheduler();   /* does not return */
    for (;;) { }             /* reached only if the scheduler could not start */
}