为什么定义没有返回类型的main()不会出错而进行编译? [英] Why does defining main() with no return type compile with no error?
问题描述
我只是通过使用GCC(g++
)进行编译来测试此代码;
I was just testing this code by compiling it with GCC (g++
);
#include <stdio.h>
main(int argc, char **argv){
printf("something");
}
它似乎可以构建并运行良好,只是发出警告;
It seems to build and run fine with just a warning saying;
ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
尽管我定义了main()
,没有返回类型,并且没有返回任何值.
然后,我决定通过使用Visual C ++编译器进行编译来测试相同的代码,但是它有效地抛出了错误:
Though I defined main()
with no return type and not returning any value to it.
I then decided to test the same code by compiling it with Visual C++ compiler but it efficiently threw the error:
missing type specifier - int assumed. Note: C++ does not support default-int
并且构建没有成功.
我期望GCC抛出错误并停止编译,而不是发出警告,并使其成功构建.
I was expecting GCC to throw an error and stop compiling instead of a warning and letting it build successfully.
为什么GCC赋予main()
这样的特权,即不让其知道其返回类型?
Why does GCC give main()
such privilege of not letting it know its return type?
推荐答案
程序格式错误. C ++标准不允许省略返回类型.
The program is ill-formed. Omitting the return type is not permitted by the C++ standard.
编译器不将其视为致命错误的原因是历史性的.在1999年标准之前,C确实允许省略函数的返回类型.它默认为int
. C ++源自C,因此早期的(预标准)C ++具有相同的规则.
The reason the compiler doesn't treat it as a fatal error is historical. Prior to the 1999 standard, C did permit the return type of a function to be omitted; it would default to int
. C++ is derived from C, so early (pre-standard) versions of C++ had the same rule.
在现代C ++中,省略返回类型是一个错误.需要编译器诊断这样的错误,但是不需要将其视为致命错误.通过显示警告,编译器就标准而言已经完成了工作.
In modern C++, omitting the return type is an error. The compiler is required to diagnose such an error, but it's not required to treat it as fatal. By printing a warning, the compiler has done its job as far as the standard is concerned.
不要忽略警告.
这篇关于为什么定义没有返回类型的main()不会出错而进行编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!