为什么 c 允许 main() 即使它不是 int main() 或 void main()? [英] Why does c allow main() even when it is not int main() or void main()?

查看:43
本文介绍了为什么 c 允许 main() 即使它不是 int main() 或 void main()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 K&R 第二版时,我注意到这些程序总是以主要的(){".我一直认为 main() 在它之前必须有 int 或 void .所以它看起来像int main()"或void main()".什么只是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?

推荐答案

main() 是旧的 K&R 样式,其中省略了 int 作为返回类型如果未指定,则默认为 int (您应该指定它).此外,空括号是 K&R 风格的,表示它不需要参数..在 C99 中,这现在应该是 void 来表示这样.空括号意味着该函数将接受任意数量的任意类型的参数,这显然不是您想要的.所以最后的结果是:

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() 应该返回 int .. 约定表示最后的 return 0; 语句将有助于向调用者表明程序执行成功 - 非 0 返回值表示异常终止.

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.

对您的问题更直接的回答是 main() { ... } 有效,因为它没有错.编译器发现 main 函数没有声明返回类型,所以它默认为 int.空括号表示 main 接受任意数量的任意类型的参数,这也没有错.但是,要符合 C99 样式/标准,请使用

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) { ... }

这篇关于为什么 c 允许 main() 即使它不是 int main() 或 void main()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆