我正在阅读一篇有关C++与C的文档。其中提到,相比于C语言,C ++写得更紧凑。举个例子,C语言允许main()
函数的类型为void,但是C++不允许。以下是标准中的相关规定:
C++标准中规定:
It shall have a return type of int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { /* … */ }
and
int main(int argc, char* argv[]) { /* … */ }
标准C语言也说了同样的话,但是还有一句额外的声明。
如果返回类型与int不兼容,则返回给宿主环境的终止状态是未指定的
这表明允许不返回int的形式是有意的。
当你有了“类型可以是实现定义的”这个声明,难道不是为C++编译器实现社区留下了允许void作为类型的余地吗?
gcc
的标准兼容性时,一定要使用-pedantic-errors
。这样,gcc 4.6.2就会显示:"error: return type of ‘main’ is not ‘int’ [-Wmain]" - Matthew Flaschen