問題描述
為什么 main()
是用戶定義的函數(shù)?
Why is main()
a user defined function ?
我什么時候使用 void main()
和 int main()
?
When will I use void main()
and int main()
?
推薦答案
EDIT 這個答案并不完整,因為它沒有真正解決奇怪的句子或其他實現(xiàn)定義的方式".我現(xiàn)在寫了一個更完整的答案它還解決了 C90、C11 和 C++.編輯結(jié)束
EDIT This answer is not as complete as it could be since it doesn't really address the strange sentence "or otherwise in some implementation-defined manner". I have now written a more complete answer which also addresses C90, C11 and C++. END OF EDIT
以下是 C 標準的說明(ISO C 9899:1999):
Here is what the C standard says (ISO C 9899:1999):
5.1.2.1 獨立環(huán)境
5.1.2.1 Freestanding environment
在一個獨立的環(huán)境中(在其中 C程序執(zhí)行可能發(fā)生沒有任何經(jīng)營利益系統(tǒng)),名稱和類型程序啟動時調(diào)用的函數(shù)是實現(xiàn)定義./../效果程序終止在一個獨立的環(huán)境是實現(xiàn)定義.
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. / .. / The effect of program termination in a freestanding environment is implementation-defined.
5.1.2.2 托管環(huán)境
5.1.2.2 Hosted environment
不需要提供托管環(huán)境,但是應(yīng)符合以下規(guī)格(如果有).
A hosted environment need not be provided, but shall conform to the following specifications if present.
5.1.2.2.1 程序啟動
5.1.2.2.1 Program startup
程序啟動時調(diào)用的函數(shù)名為主要的.實現(xiàn)聲明沒有這個函數(shù)的原型.它應(yīng)用 int 返回類型定義并且沒有參數(shù):
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) {/* ... *