Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does main() not need a return statement? [duplicate]

Tags:

c

Possible Duplicate:
return 0 implicit
Why is return 0 optional?

why does the main() function in C can terminate correctly even without using exit or return?

for example:

#include<stdio.h>

int sum(int a,int b)
{
 return (a + b);
}

int main()
{
 int a=10;
 int b=5;
 int ans;    
 ans=sum(a,b);
 printf("sum is %d",ans);
}
like image 234
freeboy1015 Avatar asked Jul 12 '26 14:07

freeboy1015


2 Answers

It's because the C99 and C11 standards says so:

5.1.2.2.3 Program termination

Reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

However, you should add a return statement. This is because the returned value is undefined in C89 otherwise!

3.6.6.4 The return statement

Reaching the } that terminates a function is equivalent to executing a return statement without an expression.

2.1.2.2 Hosted environment

If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined.

like image 193
orlp Avatar answered Jul 14 '26 12:07

orlp


Because the compiler adds an implicit exit for you.

Check nightcracker on why; still I strongly recommend you make an explicit exit/return with a meaningful return code.

C99 standard:

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;10) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

I am looking for the C89 text to check.

like image 34
Fingolfin Avatar answered Jul 14 '26 12:07

Fingolfin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!