Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c - 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,i,ans);
    }
}

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...