Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

c++ - Why does the main function work with no return value?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...