为什么int main(){}会编译?
时间:2020-03-05 18:41:58 来源:igfitidea点击:
(我使用的是Visual C ++ 2008)我一直都听说main()是返回整数所必需的,但是在这里我没有输入" return 0;",并且它编译时带有0个错误和0个警告!在调试窗口中,它表示程序已退出,代码为0。如果此函数的名称不是main(),则编译器会抱怨说" blah"必须返回一个值。粘贴" return;"也会导致错误出现。但是,将其完全排除在外,可以很好地进行编译。
#include <iostream> using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; }
这可能是VC ++中的错误吗?
解决方案
回答
我很确定VC ++如果我们在主函数中不包含一个返回值,则只会插入一个返回值0。函数也可能发生同样的事情,但是至少在这些情况下,我们会得到警告。
回答
这是C ++语言标准的一部分。如果main中没有显式的return语句,则会为我们生成一个隐式return 0。
回答
3.6.1 Main function .... 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type 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[]) { /* ... */ } .... and it continues to add ... 5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
试图找到C ++标准的在线副本,以便我能引用这段话,我发现了一篇博客文章,该文章引用的所有正确内容比我能引用的要好。
回答
第6.6.3 / 2节指出"从函数末尾流出等同于没有值的返回;这将导致值返回函数发生不确定的行为"。
一个示例是下面的代码,该代码最多在VS 2010 / g ++上给出警告
int f(){ if(0){ if(1) return true; } } int main(){ f(); }
因此,总的来说,正如先前的回答所指出的那样,"主要"是特殊的。