網頁

2012年4月5日 星期四

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

1 則留言:

  1. 這邊補充一下 StackOverflow 上那篇文章的閱讀心得。

    關於 C89/C90 所訂的 C 語言:
    - 可以只寫 main()。function 的 return type 的 int 可以不寫,因為是預設值。
    - return statement 不可省略,若省略則 return value 為 undefined。如本文中所提。

    關於 C99 所訂的 C 語言:
    - return type 不可省略。
    - 若省略 return statement 則預設視為 return 0;。(此行為與 C89 不同)

    關於 C++:
    - C99 那兩點特性也有。
    - 不可 re-enter main function。

    呃啊啊啊,那 C99 可不可以 re-enter main function 啊?XD

    回覆刪除