C, C++ 中沒有 return 敘述的 main function

今天在噗浪上討論+研究了一個問題,這邊記錄一下,不然每次查完資料都會忘記= =
相關的討論在這則噗浪上,如果有興趣也可以去看。

我所研究的問題很簡單,「在 C/C++ 語言中,main function 不寫上 return statement 的話,會怎樣?」因為有些人會寫上 void main () 這種 prototype (我想有個原因是 Visual C++ 6.0 預設就這樣搞),或是有些人寫了 int main () 但是卻沒在 main function 中寫上 return 0; 或是 return EXIT_SUCCESS;。那麼,到底會不會出現問題呢?

我在網路上找到一份號稱是 ANSI C 的 spec,希望我沒有被詐騙,該份 spec 的連結在此
根據這份文件,其中有兩個部分可以解決我的疑惑:

2.1.2.2

If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined.

3.6.6.4

If a return statement without an expression is executed, and the value of the function call is used by the caller, the behavior is undefined. Reaching the } that terminates a function is equivalent to executing a return statement without an expression.

根據以上兩個節錄出來的部分,我們知道,如果 main function 宣告 return type 為 int 且寫了沒有值的 return 的話(就是單純的 return;),那麼執行環境所收到的程式回傳狀態為「未定義的」(根據 2.1.2.2)。我們又知道,沒有寫 return statement 的話,當程式執行到 function 結尾的 } 的時候,就相當於執行了沒有值的 return。(根據 3.6.6.4)

再來,2.1.2.2 也提到這個

The function called at program startup is named main. The implementation declares no prototype for this function. It can be defined with no parameters:

int main(void) { // }

or with two parameters (referred to here as argc and argv , though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char argv[]) { /…*/ }

雖然我不敢完全肯定,但我認為,main function 的 return type 勢必要被定為 int。所以 void main () 是不被允許的才對。(此處若我對規範有誤解的話,煩請指正!)

綜合以上,如果 main function 不寫回傳值的話,在 C 語言的規範中,他的程式狀態是未定義的!

那麼 C++ 呢?

根據噗浪上提出回應的 PkmX 大大表示

C++11 3.6.5: … If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

所以說在 C++ 中,不寫 return statement 的 main function 是被視為正常結束 (return 0;) 的。

此外,在 StackOverflow 上也有得參考,連結在此。底下也很歡迎提出相關意見唷!:D


Last modified on 2012-04-05