Search code examples
c++linuxexit-code

Why can't I return bigger values from main function?


I am trying to return a bigger value like 1000 from 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?


Solution

  • 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.