为什么 C 和 C++ 中的 main 函数的类型留给用户定义?

2022-01-31 00:00:00 main c c++

为什么 main() 是用户定义的函数?

Why is main() a user defined function ?

什么时候使用 void main()int main()?

When will I use void main() and int main()?

推荐答案

EDIT 这个答案并不完整,因为它并没有真正解决奇怪的句子或其他一些实现定义的方式".我现在写了一个更完整的答案它还涉及 C90、C11 和 C++.编辑结束

EDIT This answer is not as complete as it could be since it doesn't really address the strange sentence "or otherwise in some implementation-defined manner". I have now written a more complete answer which also addresses C90, C11 and C++. END OF EDIT

以下是 C 标准 (ISO C 9899:1999):

Here is what the C standard says (ISO C 9899:1999):

5.1.2.1 独立环境

5.1.2.1 Freestanding environment

在独立的环境中(在哪个 C程序执行可能发生没有任何操作的好处系统),名称和类型程序启动时调用的函数是实现定义./../效果在一个程序终止独立的环境是实现定义.

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. / .. / The effect of program termination in a freestanding environment is implementation-defined.

5.1.2.2 托管环境

5.1.2.2 Hosted environment

无需提供托管环境,但应符合以下规格(如果有).

A hosted environment need not be provided, but shall conform to the following specifications if present.

5.1.2.2.1 程序启动

5.1.2.2.1 Program startup

程序启动时调用的函数名为主要的.实现声明没有这个函数的原型.它应用 int 的返回类型定义并且没有参数:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) {/* ... */}

int main(void) { /* ... */ }

或带两个参数(指这里是 argc 和 argv,尽管有可以使用名称,因为它们是本地的到它们所在的功能声明):

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[]) {/*... */}

int main(int argc, char* argv[]) { /* ... */ }

C++ 标准中的文本或多或少是相同的.请注意文本中的程序启动"是托管环境的子条款.

The text in the C++ standard is more or less identical. Please note that "Program startup" in the text is a subclause to hosted environment.

这意味着:

  • 如果您的程序在无主机环境中运行(您的程序是嵌入式系统或操作系统),它可能有任何返回类型.void main() 是最常见的.

如果您的程序在托管环境中运行(在操作系统之上),main() 必须返回 int,并且可能有其他参数.

If your program is running in a hosted environment (on top of an OS), main() must return int, and may have additional parameters.

相关文章