Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the main function work with no return value?

Tags:

c++

This question is out of curiosity; while writing a main for a test program, I returned nothing from main(no return statement in main). But I declared main as int main(). And it compiled successfully.

Where as if there is any other function written with a int return type and actually not returning an int,I would get an error

'Function name' must return value

So why compiler doesn't complain the same for main function?

like image 654
ZoomIn Avatar asked Oct 10 '13 10:10

ZoomIn


People also ask

What does a function with no return return?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

What is the purpose of a function that does not return a value?

In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.

Why do we use return 0 in main function?

return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false.

Does main function need return?

In C++ language, the main() function can be left without return value. By default, it will return zero.


1 Answers

Normally it is not allowed for the control flow to reach the end of a non-void function without returning something. The main function is handled differently, as specified in the standard.

From http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf:

§ 3.6.1/5

If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

As for the rationale, I'm not sure, honestly. If someone knows, please add it to my answer or as a comment.

like image 185
Tamás Szelei Avatar answered Oct 12 '22 16:10

Tamás Szelei