Previous: Floating Point Portability, Up: Portable C and C++

12.6 Exiting Portably

A C or C++ program can exit with status N by returning N from the main function. Portable programs are supposed to exit either with status 0 or EXIT_SUCCESS to succeed, or with status EXIT_FAILURE to fail, but in practice it is portable to fail by exiting with status 1, and test programs that assume Posix can fail by exiting with status values from 1 through 255. Programs on SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero status when main returned nonzero, but ancient systems like these are no longer of practical concern.

A program can also exit with status N by passing N to the exit function, and a program can fail by calling the abort function. If a program is specialized to just some platforms, it can fail by calling functions specific to those platforms, e.g., _exit (Posix) and _Exit (C99). However, like other functions, an exit function should be declared, typically by including a header. For example, if a C program calls exit, it should include stdlib.h either directly or via the default includes (see Default Includes).

A program can fail due to undefined behavior such as dereferencing a null pointer, but this is not recommended as undefined behavior allows an implementation to do whatever it pleases and this includes exiting successfully.