在 C/C++ 中编写 void main() 或 main() 可以吗?
在 C 中, void main()没有定义(合法)的用法,它有时会抛出垃圾结果或错误。但是, main()用于表示不带参数并返回整数数据类型的主函数。
定义不是,也从来不是 C++,甚至也不是 C。参见 ISO C++ 标准 3.6.1[2] 或 ISO C 标准 5.1.2.2.1。更多。
void main(){
// Body
}
符合要求的实现接受下面给出的格式:
int main(){
// Body
}
和
int main(int argc, char* argv[]){
// Body
}
一个符合要求的实现可能会提供更多版本的 main(),但它们都必须具有返回类型 int。 main() 返回的 int 是程序向调用它的“系统”返回值的一种方式。在不提供此类工具的系统上,返回值被忽略,但这不会使“void main()”合法 C++ 或合法 C。
Note: Even if your compiler accepts void main() avoid it, or risk being considered ignorant by C and C++ programmers. In C++, main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution.
例子:
CPP
// CPP Program to demonstrate main() with
// return type
#include
// Driver Code
int main()
{
std::cout
<< "This program returns the integer value 0\n";
}
C++
#include
using namespace std;
main()
{
// Body
}
This program returns the integer value 0
NOTE: Neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to C89 and ARM C++, int is not assumed where a type is missing in a declaration.
最后,
C++
#include
using namespace std;
main()
{
// Body
}
上面的代码没有错误。如果您编写整个无错误的 main()函数,最后没有 return 语句,那么编译器会自动在程序末尾添加一个具有正确数据类型的 return 语句。
综上所述,使用void main()或简单地使用 main ( ) 绝不是一个好主意,因为它不确认标准。不过,某些编译器可能允许这样做。