Exit Status Defined Constants

The tradition for successfully exiting a command line program is to use return 0; or, as I write it, return(0);. Zero is the OK value, meaning a program exited cleanly. Other values returned represent specific conditions, not necessarily errors, but information that can be communicated to the operating system or some other program.

The same value is used as the exit() function’s argument. Unlike return (which is a keyword), you can use exit() beyond the main() function to bail out. And if you want to get fancy, you can use one of two defined constants available in the stdlib.h header file: EXIT_SUCCESS and EXIT_FAILURE. Here’s some code:

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

int main()
{
    int d;

    printf("Type a positive number: ");
    scanf("%d",&d);

    if( d > 0 )
    {
        puts("Thanks!");
        return(EXIT_SUCCESS);
    }
    else
    {
        puts("Wrong!");
        return(EXIT_FAILURE);
    }
}

You don’t need to look up the defined constants’ assigned values because I already did: zero for EXIT_SUCCESS and 1 for EXIT_FAILURE, but that’s not the point of using them.

Like many things in C, it’s a good idea to use constants wherever possible. That way you can universally change a value by making a single modification to your code. The same thinking holds true for the exit constants. Though it’s highly unlikely, at some point in the future an operating system may accept a value such as -1 meaning “exit successful.” If such a thing came to pass (and it won’t), you would have to update all your legacy code, scanning for return and exit() points and changing the values as necessary.

On the other hand, if you create code that uses the exit constants, compiling on the new operating system wouldn’t present an issue; the EXIT_SUCCESS constant would be updated for the operating system’s C compiler and no changes would be necessary.

You can also define these constants in code that doesn’t require the stdlib.h header file. The following preprocessor directives do the trick:

#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif

The above directives, either at the start of the source code file or in a user-defined header file, are all that’s needed to create the constants. And when that operating system that requires a -1 return value for a program comes around (and it won’t), you’re ready to compile your compatible code.

For assistance on the preprocessor directives, see my Preprocessor Directives page here on the C For Dummies Blog.

Leave a Reply