Note that I am running a linux machine, although I don't think the result is different on a windows (or other) machine.
This is a simple question - C++ programs usually return a 32 bit int. If I return -1
, and then print the result from the terminal, the result is 255
.
Why is this? I feel link this is something I should know, or should have noticed many years ago - I never really used return codes before now or thought about it before.
Test C++ program:
int main()
{
return -1;
}
Compile:
g++ main.cpp -o a.out
Run:
./a.out
Check result:
echo $?
Result:
255
I would have expected to see 2^32 - 1.
Why is the result 255
not -1
or even 4294967295
. (2^32 - 1
)
Because (not all) OS's use the whole return value. In this case, it's truncated to the low 8 bits. It's up to the OS (and other related components, such as the shell) to "use" and "retain" this value, and it's what's called an "implementation detail", in other words, the C and C++ standards do not dicate what the usefulness or meaning of the return value is [aside from the paragraph below] - just that from the C perspective it is an int
- the C program may be started in an environment where that value is ignored, truncated, extended or multiplied by 432 and it's still a valid C or C++ environment.
The C standard says that the value 0
or EXIT_SUCCESS
(which should have the value zero as I understand it) and the value EXIT_FAILURE
(some non-zero value) should be considered success and failure respectively. However, all other values are "implementation defined" and thus under the rules of the OS/environment that the execution happens in.
Note that when the shell (or whatever runs your program), it does not jump straight to your main
, but some other functionality is performed first to initialize things that are needed by your main
function. And once main
has returned/exited, there is usually some code that executes AFTER your program as well. Exactly how this works is dependent on several things:
The C and C++ standard doesn't define these things, as doing so would potentially affect the actual platforms that can/will run C and/or C++ applications, and the goal of C and C++ is to "be inclusive" - in other words, try to not limit the environment, processor, etc that the languages support.
The return value is defined as an int, but legal values for exit codes are only 0-255.
You can think of it as if the operating system is doing (unsigned char)main() internally.
Added explanation per comment request:
exit
function documentation). Different operating systems may have different opinionsmain
. It also takes care of accepting the return value and calling exit(your_return_value)
. But as others have noted, this is an implementation detail, not part of the C standard (there is difference between C and posix, althought they overlap).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With