gpt4 book ai didi

c - 各主要功能有什么区别?

转载 作者:行者123 更新时间:2023-11-30 20:29:15 24 4
gpt4 key购买 nike

C 中 main、void main 和 int main 之间有什么区别?他们每个人都做什么?还有什么是 return 0;用于?我知道它以某种方式告诉操作系统程序已成功完成,但这能提供什么?我想指出的是,我在 C 上工作了一个多月了,所以我并没有真正的经验

最佳答案

5.1.2.2.1 Program startup

1 The function called at program startup is named <strong>main</strong>. The implementation declares noprototype for this function. It shall be defined with a return type of int and with noparameters:

    int main(void) { /* ... */ }
or with two parameters (referred to here as <strong>argc</strong> and <strong>argv</strong>, though any names may beused, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
or equivalent; 10) or in some other implementation-defined manner.
10) Thus, <strong>int</strong> can be replaced by a typedef name defined as <strong>int</strong>, or the type of argv can be written aschar ** argv, and so on.

C 2011 Online Draft

main()相当于 int main(void) 。在该语言的早期版本中,如果您定义的函数没有显式返回类型,则编译器假定它返回 int 。另外,如果您定义一个不带任何参数的函数,则意味着该函数没有任何参数。不再允许隐式类型,并且使用原型(prototype)语法允许您在编译时捕获参数数量和类型的错误,因此不应再使用这种形式。

void main()不是标准的,除非您的实现明确将其记录为 main 的有效签名,否则不应使用(“或以其他某种实现定义的方式”)1。否则,使用它会导致未定义的行为,这可能会导致您的代码在启动或退出时行为异常。在某些平台上,它的运行没有明显问题,但您不应该相信这是真的。

5.1.2.2.3 Program termination

1 If the return type of the <strong>main</strong> function is a type compatible with int, a return from theinitial call to the main function is equivalent to calling the exit function with the valuereturned by the main function as its argument; 11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, thetermination status returned to the host environment is unspecified.
11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in <strong>main</strong>will have ended in the former case, even where they would not have in the latter.

C 程序向运行时环境返回状态代码 - 在 *nix 和类似平台上,返回代码 0 表示成功、正常的程序终止。 stdlib.h定义宏 EXIT_SUCCESSEXIT_FAILURE ,应该使用它来代替文字数值:

#include <stdlib.h>
...
int main( void )
{
...
if ( something_bad_happens )
return EXIT_FAILURE;
...
return EXIT_SUCCESS;
}

<小时/>

  1. 即使如此,我也不会使用它,因为它保证是不可移植的。

关于c - 各主要功能有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58597992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com