一、依據
C++標準規(guī)定: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. 該規(guī)則僅僅對main函數適用。
3. 對其他函數,如果省略返回值, 將得到一個警告。
4. 應該避免3的情況。
二、 示例
二、1. 一個合法的最小化的完整C++程序如下:
int main() {}
二、2. 省略的確切含義
同時,標準中的用語是很
考究的:
“當控制到達main結束處時沒有遇到return語句,效果與返回0相同”。
即是說,標準規(guī)定的是“對省略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. 對于其他函數,沒有這種“優(yōu)待”
如:
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

本作品采用知識共享署名-非商業(yè)性使用-相同方式共享 2.5 中國大陸許可協議進行許可。
轉載請注明 :
文章作者 - OwnWaterloo
發(fā)表時間 - 2009年04月26日
原文鏈接 - http://www.shnenglu.com/ownwaterloo/archive/2009/04/26/omit_return_in_main.html
posted on 2009-04-26 14:37
OwnWaterloo 閱讀(3448)
評論(1) 編輯 收藏 引用