在他们使用的一本书(不记得是哪一本)中:
void main(void)
在学校我学到:
int main(void)
有没有什么情况下实际上void main(void)是正确的?或者至少没有明确错误?
编辑:根据自 C99 以来提出的答案,这是不正确的。早期版本呢?它是明确错误的还是只是什么也没说?为什么 C 编译器不抱怨它?
Per the C standard
C99 §5.1.2.2.1 Program startup
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) { /* ... */ }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;10 or in some other implementation-defined manner.
10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char **argv, and so on.
The closing clause grants implementations their own vices, which is to say, if a program does not follow this, it is no longer standard-compliant and instead reliant on the implementation for compatibility. If you want your main() to work everywhere, follow one of these and you'll be ok.
永远,永远使用void main(void). 这不是标准的。
始终使用其中之一
int main(void);
int main();
int main(int argc, char **argv);
int main(int argc, char *argv[]);
而这本书的最佳用途是用它来点燃你冬天的第一把火。
void main(void)一些(全部?)C编译器允许。但是,无论如何都不应该使用它。因为至少从 C99 开始是不允许的。但是,我没有找到抱怨它的 C 编译器。
例如 void.c:
#include <stdio.h>
void main(void)
{
printf("hello world");
}
gcc void.c
编译。还要检查http://www.compileonline.com/compile_c_online.php
所以总而言之(即使我没有找到参考资料):在最早的 C 版本void main(void)中可能没有被禁止。
但是: 如果不指定返回值,您现在就不会返回程序返回的内容。因此,无论标准与否、正确或错误,都不要使用它,因为它会使您的程序具有不确定性。