作者:SuperSodaSea
鏈接:https://www.zhihu.com/question/51597277/answer/126602590
參考標准:
C11(ISO/IEC 9899:2011)
C11 5.1.2.2.3 Program termination
![]()
……如果 main函數的返回值是一個與 int兼容的值,那么 main函數的初始調用的返回相當於用 main函數的返回值作為參數調用 exit函數;
到達終止 main函數的 }時會返回0。……
TL;DR:main函數不寫return默認返回0。
----------------分割線----------------
補充一下不是main的情況:C11 6.9.1 Function definitions即使在x86中返回值的確存放在eax寄存器中,實際使用中也不應該依賴這種未定義行為。編譯器一般會扔給你一個警告,比如:
如果到達終止函數的 },且函數調用的值被調用者使用,則行為未定義。
[Warning] no return statement in function returning non-void [-Wreturn-type]
下面這段英文描述是從C99標准的PDF文檔上復制下來的:
5.1.2.2.1 Program startup
The called at program startup is named main.The implementation declares no
prototype for this .It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with twoparameters (referred to here as argc and argv,though anynames may be
used, as theyare local to the in which theyare declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9)or in some other implementation-defined manner.
從C99標准的規定里可以看出,main函數的標准定義一般為這兩種形式:
第一種形式:
int main (void)
{
……
return 0;
}
第二種形式:
int main (int argc, char *argv[ ])
{
……
return 0;
}

如果到達終止函數的
},且函數調用的值被調用者使用,則行為未定義。