clinuxunspecified-behavior

Why does a main function without a return statement return value 12?


I have written a program that prints a table. I have not included the return syntax in the main function, but still whenever I type echo $? it displays 12.

My source code :

#include <stdio.h>


int main(void)
{
    int ans,i,n;
    printf("enter the no. : ");
    scanf("%d",&n);

    for(i=1;i<=10;i++)
    {
        ans = n*i;
        printf("%d * %d = %d\n",n,i,ans);
    }
}

I have not written return 12, but still it returns 12 every time I execute the program.

Thanks.


Solution

  • As swegi says, it's undefined behavior. As Steve Jessop et al say, it's an unspecified value until C89, and specified in C99 (the observed behavior is non-conformant to C99)

    What actually happens in most environments is that the return value from the last printf is left in the register used for return values.

    So it'll be 11 for n == 0, 12 if n is one digit, 14 for two digit n, 16 for three digit n, etc.