views:

232

answers:

2

I am trying to return a bigger value like 1000 form my main function, but when I type echo $? it displays 0.

If I return a smaller value like 100 it displays the correct value.

My Code :

int main(void)
{
     return 1000;
}

Is there any limitation on the values which we can return ?

Thanks.

+16  A: 

There are two related concepts here: C exit status, and bash return code. They both cover the range 0-255, but bash uses numbers above 126 for it's own purposes, so it would be confusing to return those from your program.

To be safe limit exit status codes to 0-127, as that is most portable, at least that is implied by http://docs.python.org/library/sys.html#sys.exit.

The C exit status is put into the bash $? variable after execution, but bash uses 127 to indicate 'command not found' so you may want to avoid that. Bash reference page.

Bash also uses 128-255 for signals - they indicate the process was killed with a signal: exit code = 128 + signal number. So you might be able to get away with using numbers close to 255 as it unlikely that signal numbers will go that high.

Beyond those common guide-lines there are many attempts to define what different numbers should mean: http://tldp.org/LDP/abs/html/exitcodes.html.

So it you want to return an arbitrary integer from your program, it's probably best to print it to stdout, and capture it with VALUE=$(program) from your bash script.

Douglas Leeder
Gah, Leedered...
Jon Skeet
I believe the range is 0-255 (i.e. the range of `uint8_t`) on *NIX systems--not familiar with any systems with a max value of 127 (that would imply a signed return type equivalent to `int8_t`, but that would also imply a lower bound of -128.)
Jonathan Grynspan
+1 Thanks for the explanation : )
Searock
Besides telling an incorrect range (as @Jonathan noted), you also seem to confuse the program exit status (as reported by `waitpid(2)`) and the shell command exit status (as reported by `$?`). "128-255 are used for signals" only applies to the latter.
Roman Cheplyaka
+3  A: 

The return value of main (i.e. the exit status of the application) is limited to the range [0, 255] on *NIX. 1000 is out of range, and the OS treats it as 0, presumably.

Jonathan Grynspan
No, at least in bash, an exit status greater than 255 returns the value modulo 256. 1000 will return 232
stefano palazzo
That's what I would assume, based on how C handles numbers, but the OP said he was getting 0 as his result.
Jonathan Grynspan