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?
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.
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.
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.
In C++ language, the main() function can be left without return value. By default, it will return zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With