posts - 16,  comments - 34,  trackbacks - 0

一、依据

C++标准规定:main函数可以省略返回语句,等效于返回0。

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;

                ——ISO C++03 3.6.1 Main function p44/72
                ——ISO C++98 3.6.1 Main function p43/69

注意:
1. main函数的返回类型是int, 不是void或者其他类型。
2. 该规则仅仅对main函数适用。
3. 对其他函数,如果省略返回值, 将得到一个警告
4. 应该避免3的情况。




二、 示例

        二、1. 一个合法的最小化的完整C++程序如下:
int main() {}

        二、2. 省略的确切含义

同时,标准中的用语是很考究的:
“当控制到达main结束处时没有遇到return语句,效果与返回0相同”。

即是说,标准规定的是“对省略return的分支,认为返回0”。
同时,标准也允许其他分支含有返回语句。
如下:
int main(int argc,char* []) {
    
switch (argc)
    {
    
case 1:
        
// error, should passing argument
        return -1;
        
// parse arguments
    default:
    
case 3// parser argv[2]
    case 2// parser argv[1]
        ;
    }
    
// do some work
    
// control reaches here
}

没有输入命令行参数时, 返回一个错误。
其他情况,当控制达到main的结尾处时,效果同return 0;

        二、3. 对于其他函数,没有这种“优待”
如:
int not_main(int argc) {
    
if (argc<=1)
        
return -1;
}
int main(int argc,char* []) {
    
return not_main(argc);
}

not_main无疑将得到一个警告。
程序在没有输入命令行参数时的返回值将无法预知



三、验证

        三、1. ERRORLEVEL

windows下,可以通过 %ERRORLEVEL% 查询上一次程序返回值。

结果与判断相吻合:
1. minimalist有确定的返回值0
2. omit_return_in_main有确定的返回值-1或0
3. 对omit_return_in_other
3.1 有命令行参数时,返回值确定为0。
3.2 无命令行参数时,返回值无法预知


        三、2 汇编代码

更严谨的验证方法是查看汇编代码。

可以看到,在minimalist与omit_return_in_main的main函数中都有将eax置0的代码。
在omit_return_in_other中的not_main函数中,没有这样的代码。




四、 例外

VC6在这点上与标准不符。

        四、1. 对omit_return_in_main,它给出的警告:

warning C4715: 'main' : not all control paths return a value

说明它在这点上与标准不符。
显然,在有命令行参数的时候,程序结果无法预知


        四、2. 对minimalist,它给出的警告很搞笑:

warning C4508: 'main' : function should return a value; 'void' return type assumed

暴露出它另一个与标准不符的地方——main返回void。
显然,任何情况下,程序结果都无法预知

        四、3. 对omit_return_in_other,是程序员的错误。




五、 实践

不知道为什么C++标准在这里开一个“后门”。
——C++在许多地方都是很严谨的。

在实际应用中,尽量不要采用这一特性, 因为:
1. 旧编译器不支持
2. C不支持——如果希望main能同时按C语言编译的话

对于演示用的C++代码,与主题无关的代码行能省则省,则可以使用这一特性。
比如:C++标准中的示例代码几乎都采用了这一特性。
由此可得出,C++标准在这里开后门的原因是——让C++标准更薄^_^



相关链接:

——示例代码
http://immature.googlecode.com/svn/trunk/iMmature/sample/omit_return_in_main



Creative Commons License
作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。

转载请注明 :
文章作者 - OwnWaterloo
发表时间 - 2009年04月26日
原文链接 - http://www.cppblog.com/ownwaterloo/archive/2009/04/26/omit_return_in_main.html

posted on 2009-04-26 14:37 OwnWaterloo 阅读(3319) 评论(1)  编辑 收藏 引用

FeedBack:
# re: main函数中省略返回语句[未登录]
2013-04-14 23:22 | null
LOL  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2013年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(8)

随笔档案(16)

链接

搜索

  •  

积分与排名

  • 积分 - 194889
  • 排名 - 132

最新随笔

最新评论

阅读排行榜

评论排行榜