为什么我们不应该使用void main()这种错误的写法

您所在的位置:网站首页 void函数不写return 为什么我们不应该使用void main()这种错误的写法

为什么我们不应该使用void main()这种错误的写法

#为什么我们不应该使用void main()这种错误的写法| 来源: 网络整理| 查看: 265

前言

在国内的某些C程序设计语言教材与专业授课过程中,流传着形如void main()的主函数写法,但无论在标准意义上抑或功能性上衡量,这种写法实然是错误的,为什么错误?如何写才是正确的?本文主要讨论这两个问题。

为何错误 不符标准 无论在 C90/C99/C11 各版本的标准中,我们都无法找到void mian()这种错误的写法。并且事实上,标准已经指明了正确的写法。

尤其是,通常以 void 为返回类型声明 main() 的习惯是完全错误的 [^出处]

void main()在功能性上是不可接受的 程序在结束时,应当向其所处的环境返回其运行状态,而不是悄然结束、不返回任何值。

Programs should return status to their environment. [^出处]

void main()是未定义行为(Undefined Behaviour) 对于未定义行为,如何处理将相应地由编译器做出决定,而非程序编写者。如果编译器做出了错误的决定,程序将会失败。我们已经拥有正确的写法。 正如上文所提到的,在C语言标准中,我们对于主函数拥有正确的标准写法,而不是没有规定。 什么是正确的写法

C语言标准语法是int main(void),任何实现都必须支持: int main(void) { /* ... */ } 或 int main(int argc, char* argv[]) { /* ... */ }。

The function called at program startup is named main… It shall be defined with a return type of int and with no parameters or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): int main(int argc, char argv[]) { / … */ } or equivalent; or in some other implementation-defined manner. [^出处]

本文作者: yakuback 本文链接: https://yakuback.github.io/2020/03/08/为什么我们不应该使用void-main-这种错误的写法/ 版权声明: 译文使用 署名-非商业性使用-相同方式共享 许可协议. 如需转载,请您注明出处.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3