Skip to content
Tutorials Center
My learning

Topics

C Reference ยท stdlib.h

C EXIT_SUCCESS and EXIT_FAILURE

Reference for C EXIT_SUCCESS and EXIT_FAILURE: what program exit status means, how main's return value reaches the shell, and conventions for custom codes.

EXIT_SUCCESS and EXIT_FAILURE are macros from <stdlib.h> that name the two portable exit statuses. Pass one of them to exit() or return it from main to tell the program that started you (a shell, a build script, another program) whether the run worked.

On nearly every system EXIT_SUCCESS is 0 and EXIT_FAILURE is 1, but the standard does not promise those numbers, which is why the names exist. The value 0 is also always accepted as success.

C
#include <stdlib.h>

int main(void)
{
    return EXIT_SUCCESS;
}

Try it

C Returning a status from helper functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Custom exit codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#define EXIT_SUCCESS /* implementation-defined, usually 0 */
#define EXIT_FAILURE /* implementation-defined, usually 1 */

Both expand to integer constant expressions usable as the argument of exit() or as the return value of main.

Name Description
EXIT_SUCCESS The program finished successfully.
EXIT_FAILURE The program failed.

Returns: not functions; they are values. The host environment receives the status when the program ends.

Errors / undefined behavior: values other than 0, EXIT_SUCCESS and EXIT_FAILURE have implementation-defined meaning.

Usage notes

  • Shell convention: 0 means success, anything else means failure, so if tool; then ... and tool && next work. Use echo $? in a Unix shell, or %ERRORLEVEL% in cmd.exe, to see the status.
  • Only the low 8 bits count on Unix. exit(256) looks like 0 and exit(-1) looks like 255. Stay within 0 to 255.
  • Reserved ranges: shells use 126 (found but not executable), 127 (command not found) and 128+N (killed by signal N). Pick custom codes in the 2 to 125 range, and document them.
  • Falling off the end of main returns 0 since C99, but only main has this rule. Writing return EXIT_SUCCESS; explicitly makes the intent obvious.
  • return from main equals exit. Cleanup handlers and stream flushing happen either way.
  • Why not just 1: not all systems agree. On OpenVMS, for example, the success and failure numbers differ from Unix. The macros keep portable code correct.
  • Print errors to stderr, not to stdout, so scripts can separate diagnostics from output.