4

I compiled a two simple programs in c++ using making minor changes in each one and used the query echo $? to output the value returned to the OS by main.

Program 1

    int main()
    {
          return 0 ; 
    }

Program 2

   int main()
   {
       return -1 ; 
   }

When I ran the first program and did echo $? the value was as expected 0, but when I ran the second program and did echo $? the value was 255 instead of the expected -1.
Why is this so?
I am using Ubuntu 12.04 LTS in case it matters

Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97
  • 3
    Linux only uses the least significant 8 bits of the return from `main()` and treats it as a unsigned number. – Michael Burr Jan 21 '14 at 06:05
  • 1
    @MichaelBurr: You should post that as the answer (I was just about to). – Ed S. Jan 21 '14 at 06:06
  • possible duplicate of [What is the valid range for program return value in Linux/bash?](http://stackoverflow.com/questions/8082953/what-is-the-valid-range-for-program-return-value-in-linux-bash) – Ed S. Jan 21 '14 at 06:09

2 Answers2

4

From the POSIX spec for exit():

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.

And per the C standard:

a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
1

Linux uses only a byte of the return value. There is a very good, although somewhat lengthy explanation in the answer here. Check the one not marked as answer.

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142