Search code examples
c++functionreturn-value

Why are integer return values (such as -1 or 0) used in C and C++?


When I read C or C++ code, I often notice that functions return integer values such as -1 or 0. My question is: why are these integer return values used?

It appears that -1 is returned by functions when they are unable to do what they were intended to do. So are these values like HTTP response status codes? If so, how many other values exist and what do they represent?


Solution

  • I assume that you refer to the return value of main. This is what the C++ standard says about it:

    [basic.start.main]

    A return statement ([stmt.return]) in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std​::​exit with the return value as the argument.


    [support.start.term]

    [[noreturn]] void exit(int status);
    

    Effects:

    • ...
    • Finally, control is returned to the host environment. If status is zero or EXIT_­SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_­FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

    So, the meaning of the return value is largely implementation-defined.

    Many operating system (such as Linux, Windows, Mac, etc.) shells have a concept of "exit status code". Typically, implementations of C++ forward the returned value as the exit status code. The meaning of such status may depend on the environment where the program runs.

    For example, this is what the manual of bash (which is a shell for Linux) says:

    ... Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. ...

    For the shell’s purposes, a command which exits with a zero exit status has succeeded. A non-zero exit status indicates failure.