Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm new into C++ programming and I have a very basic question. I've noticed that when I return -1 in C++ program and then check the exit status, I get 255. Why is that?

The code is the most basic:

int main()
    {
        return -1;
    }

Then, after running the compiled code:

echo $?
255
share|improve this question

2 Answers 2

up vote 13 down vote accepted

Because in UNIX/POSIX, the exit code of a program is defined to be an unsigned 8-bit value. Converting -1 to unsigned 8-bit gives 255.

Edit to add:

To give more detail: the wait*() family of system calls in UNIX encode the result of a process into a single 32bit integer. The 32 bits of that result are further broken up to provide information such as whether the process dumped core, exited due to a signal (and which one), etc. Of that 32 bits, only 8 are reserved for the exit code of the process and those are interpreted as an unsigned value.

The fork/exec/wait model of UNIX/POSIX is one of its very oldest and most deeply embedded features; if you were designing a new operating system today you might do something different (at least use 64 bits :-)).

On the other hand, practically speaking is it really useful to have >255 exit codes? I doubt it. If you really wanted something more powerful I'd suggest that you'd switch to an "exit string", instead of a numeric exit code with a wider range.

share|improve this answer
    
Nice edit. Thanks for that additional information. –  uther May 4 '12 at 17:06
    
Thank you for your detailed answer! –  Eugene S May 4 '12 at 20:15

To quote from bash man page on EXIT STATUS

The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range. Under certain circumstances, the shell will use special values to indicate specific failure modes.

So it caps it to that range, I'm actually as surprised as you are.

From the waitpid (2) man page:

WEXITSTATUS(status)

returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.