Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is return 0 optional?

Tags:

Why, if I write

int main()  {      //...  } 

do I not need to write return 0; at the end of the main function? Does the compiler do it for me?

I use GCC / C99.

like image 596
AnyWay Avatar asked Nov 09 '10 21:11

AnyWay


People also ask

Why do we need to write return 0?

return 0: A return 0 means that the program will execute successfully and did what it was intended to do. return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.

What happens if I dont use return 0?

Short Answer: Nothing. Better Answer: return 0 it's used in main like a signal for know the exit of program was a success when return 0 executes. Best Answer: Still nothing because compilers already "put" return 0 in the the end of your code if you not explicit.

Why is return 0 always the last statement of the int main function?

The main function is generally supposed to return a value and after it returns something it finishes execution. The return 0 means success and returning a non-zero number means failure. Thus we "return 0" at the end of main function.

Can a program run without return 0?

Basically, yes. Functions are not required to return anything, even if they declare a return type other than void . The value returned will be undefined.


1 Answers

C99 and C++ special case the main function to return 0 if control reaches the end without an explicit return. This only applies to the main function.

The relevant bit of the C99 spec is 5.1.2.2.3 for the main special case

5.1.2.2.3 Program termination

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; reaching the } that terminates the main function returns a value of 0.

6.9.1/12

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

You can test this out with gcc:

int foo ( void ) { } int main( void ) { } 

C89 mode ( errors for both functions ):

sandiego:$ gcc src/no_return.c -std=c89 -Wall  src/no_return.c: In function ‘main’: src/no_return.c:2: warning: control reaches end of non-void function src/no_return.c: In function ‘foo’: src/no_return.c:1: warning: control reaches end of non-void function 

C99 mode ( main is a special case ) :

sandiego:$ gcc src/no_return.c -std=c99 -Wall src/no_return.c: In function ‘foo’: src/no_return.c:1: warning: control reaches end of non-void function 
like image 140
Pete Kirkham Avatar answered Jan 02 '23 22:01

Pete Kirkham