Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I omit return from main in C? [duplicate]

Tags:

c

main

c99

In C++, 3.6.1 Main function

(3.6.1/5) A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

Can I do the following in C99 without return 0?

int main() { }
like image 451
user963241 Avatar asked Nov 24 '12 20:11

user963241


People also ask

Does C main need a return?

In a main function, the return statement and expression are optional.

Does main in C have to return int?

The C++ standard explicitly says "It [the main function] shall have a return type of type int , but otherwise its type is implementation defined", and requires the same two signatures as the C standard to be supported as options.

What happens if I don't use return 0 in C?

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.

Do you have to return 0 in main in C?

As the user-defined function declaration mandates return 0, so we must utilize return 0, or return -1 within each C program. If we wouldn't directly declare a value, the assembler automatically includes a return 0; so it is optional to insert a return 0.


1 Answers

Yes, as of C99, reaching the } at the end of main returns 0 if the return type of main is compatible with int.

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;11) 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.

like image 61
Daniel Fischer Avatar answered Oct 10 '22 19:10

Daniel Fischer