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?
CodePudding user response:
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.
CodePudding user response:
One level up, if your program's main()
returns 0, that is considered success by the calling shell, making it useful in scripting.
The tradition of 0
for success and non-zero to indicate some kind of error state continued from there.
CodePudding user response:
This practice comes from C. Since C does not support exceptions, programmers often use return values as a status that indicates if the function succeeded or not. Some programs use error
or status
arguments instead, and set them to an error or status code appropriately.
In C , when throwing an exception isn't appropriate (for example, within a destructor), programmers often use these status codes as a way to safely handle runtime errors.
There isn't a standard or guidelines about how to implement status codes and generally it depends in the programmer. If you're interested in knowing what these status codes mean you should check the reference for the application/library you're using.