Topics / C Programming / Q37
What is the difference between exit() and return from main?
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;returnonly leavesmainwhen written inmain.- After
returnfrommain,main's local variables are gone beforeatexithandlers run, so a handler must not use pointers to them (for example, asetvbufbuffer that is a local array inmain). - Exit status:
EXIT_SUCCESS(0) andEXIT_FAILURE; only the low 8 bits reach the parent on POSIX. - In a multi-threaded program,
exit()(or returning frommain) 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 callsexit(), 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 */
}