首页 > C/C++语言 > C/C++基本语法 > [翻译]我能写"void main()"吗?
2006
01-03

[翻译]我能写"void main()"吗?

[原文]
Can I write “void main()”? By Bjarne Stroustrup 

The definition
   void main() { /* … */ }


is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. A conforming implementation accepts
   int main() { /* … */ }


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


A conforming implementation may provide more versions of main(), but they must all have return type int. The int returned by main() is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main()” legal C++ or legal C. 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. For example:


   #include<iostream>


   int main()
   {
      std::cout << “This program returns the integer value 0\n”;
   }


Note also that 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. Consequently:
   #include<iostream>


   main() { /* … */ }


is an error because the return type of main() is missing.


[翻译]
定义
void main() { /* … */ }
从来不是C++的一部分了,也不是C的一部分。看ISO C++ 标准 3.6.1[2] 或ISO C 标准 5.1.2.2.1。一个可接受的符合执行(标准)的是
    int main() { /* … */ }

    int main( int argc, char* argv[] ) { /* … */ }
一个符合执行(标准)可能预定了很多main()的版本,但它们必须都要返回类型int的值。main()返回int值是程序返回一个值给调用它的”系统”的一个方法。在系统里没有预定可以忽视这样一个简单的返回值、但却规定了不使”void main()”成为合法的C++或合法的C。即使你的编译器接受”void main()”无返回,或想冒被C/C++程序员不尊重。


在C++里,main()不需要包含一个显式的返回声明。在那种情况下,返回值是0,表示成功执行了。比如:
 #include<iostream>


 int main()
 {
  std::cout << “This program returns the integer value 0\n”;
 }
注意所有的ISO C++和C99都不允许你同意类型超出定义。这里是和C89以及ARM C++比较,当定义时没有指定类型时并不假定返回是”int”型。从而:
 #include<iostream>


 main() { /* … */ }
是个错误因为main()的返回类型没有指定。

xstar38726.6950231481


[翻译]我能写"void main()"吗?》有 1 条评论

  1. coolker 说:

    郁闷了.还是蛮多人这么写的..

留下一个回复