1

When we execute any C program in unix/linux without returning any value, shell returns some value.

In my case, it returned 11

My program is simple:

main(){
    printf("Hello World");
}

Output:

Hello World
Shell returned 11

Where to see the description of "Shell returned 11"

  • 2
    This is not a valid C program, since it doesn't declare the `main` function correctly. A conforming *standard* C implementation would return a "success" state. – Kerrek SB Dec 31 '13 at 12:41
  • 2
    you are doing wrong thing, printf("Hello World"); printf is reading 11 bytes .thats what echo $? is showing you – user2760375 Dec 31 '13 at 12:49
  • With C99 or C++ the return value will default to 0. Otherwise the return value is undefined. The fact that you got 11 is just meaningless. Return a value if you want to see the result using $? from the shell – Brandin Dec 31 '13 at 13:37

3 Answers3

4

On Unix and Linux systems, the value returned to the shell by a C program is either

  • 256+the signal number if the program terminated due to a signal
  • the lowest 8 bits of the value passed to a call to exit or _exit
  • the lowest 8 bits of the value in a return statement in main
  • if compiled with a C99-standard compiler and main is declared to return a value compatible with int, then falling off the end of main will result in an exit value of 0.
  • undefined behavior

In your case, it was undefined behavior. It looks like the return value from printf was 11, because that's the number of characters that were written. Since there were no intervening function calls between the call to printf and the end of main, this value remained in the register where function return values are stored.

You can't rely on this behavior. It will vary depending on the compiler, runtime library, and operating system. It is best to call exit or to use a return statement in main with a value.

There are some conventions for exit code values. See Are there any standard exit status codes in Linux.

Community
  • 1
  • 1
Mark Plotnick
  • 9,598
  • 1
  • 24
  • 40
0

The compiler understood implicitly that main returns an int. You should compile with -Wall to this warning (and many other useful ones). Change to:

int main(){
    printf("Hello World");
    return 0; // success
}

Or:

void main(){
    printf("Hello World");
    // returns zero to the shell unless exit(SOME_NON_ZERO_VALUE) was called
}
egur
  • 7,830
  • 2
  • 27
  • 47
0

It is the string(passed in "" to printf function) length returned by shell.

Answer posted by Mark Plotnick is right as I verified it and tried with different parameters to printf() function.

Thank you all for your replies.