关于c ++:为什么int main(){}会编译?

关于c ++:为什么int main(){}会编译?

Why does int main() {} compile?

(我使用的是Visual C ++ 2008)我一直听说main()是返回整数所必需的,但是在这里我没有放入return 0;,并且它编译时出现0个错误和0个警告! 在调试窗口中,它表示程序已退出,代码为0。如果此函数的名称不是main(),则编译器会抱怨说" blah"必须返回一个值。 粘贴return;也会导致出现错误。 但是将其完全排除在外,可以很好地编译。

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main()
{
    cout <<"Hey look I'm supposed to return an int but I'm not gonna!
"
;
}

这可能是VC ++中的错误吗?


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:

1
int main() { /* ... */ }

and

1
2
3
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 ++标准的在线副本,以便我可以引用这段话,我发现了一篇博客文章,引用的所有正确内容比我能引用的要好。


这是C ++语言标准的一部分。 如果main中没有显式的return语句,则会为您生成一个隐式return 0。


我很确定VC ++会在主函数中不包含返回值的情况下仅插入返回值0。 函数也可能发生同样的事情,但是至少在这种情况下,您会得到警告。


第6.6.3 / 2节指出:"从函数的结尾流出就等于没有值的返回;这导致在值返回函数中出现未定义的行为。"。

一个示例是下面的代码,该代码最多在VS 2010 / g ++上给出警告

1
2
3
4
5
6
7
8
9
10
int f(){
   if(0){
      if(1)
         return true;
   }
}

int main(){
   f();
}

因此,正如前面的答复所指出的那样,整体而言,"主要"是特殊的。


推荐阅读