Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

syntax - Why does c allow main() even when it is not int main() or void main()?

While reading the K&R 2nd edition I noticed that the programs always began with "main(){". I had always thought that main() had to have int or void before it. So that it would look like "int main()" or "void main()". What is just "main()" and what is the difference?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

main() is the old K&R style where the int was omitted as the return type defaults to int if not specified (you should specify it). Additionally, empty parentheses is in K&R style to show it takes no arguments.. in C99 this should now be void to indicate such. Empty parentheses means that the function will accept any number of arguments of any type, which is clearly not what you want. So the final result is:

int main(void) { ... }

main() should return int.. convention says a return 0; statement at the end will help indicate to the caller that the program executed successfully - non-0 return values indicate abnormal termination.

A more direct answer to your question would be that main() { ... } works because it's not wrong. The compiler sees that no return type was declared for the main function so it defaults to int. The empty parentheses indicates to it that main takes any number of arguments of any type, which is not wrong either. However, to conform to C99 style/standard, use

int main(void) { ... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...