作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题[标准] main() 的 prototype
时间Mon Jun 13 23:08:01 2005
据 C++ 标准,main() 这个主函式应该这样写
int main()
{
//...
return 0; // 正常结束的话就传回 0
}
或是
int main(int argc, char* argv[])
{
//...
return 0;
}
每种编译环境至少要能支援上述两种 main(), 要支援更多参数的
main() 则由其自订。像有的环境会支援第三个参数,传环境变数
的值。
网路上、书本上,常见有人写
void main()
甚至是
main()
这些都是不合标准的,不但不合 C++ 标准,也不合 C 标准(C99)。
有一点很特殊的是,虽然标准要求要以 int 做传回的 type, 但
是不要求一定要明文写 return 0; 标准文件的 3.6.1/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;
所以 main 中不写 return 叙述是正确的。当然,只有 main 才这样,
其他的 function, 若是 return type 不是 void, 都要写 return 叙述。
以上是澄清一些许多人搞不清楚,但其实很基本的东西。他们会搞不
清楚,实在是受到个别不良编译器及书籍的误导。令人 Orz 的 VC++ 6.x
听说就是这样。该 warning 的不 warning ( void main ), 不该 warning
的在那里嚷嚷 ( main 中没写 return )。
main 还有一些相关细节,先写到这里。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.208.166
1F:推 Eventis:没有回传值的函数预设不是为int吗@.@? 61.62.49.43 06/13
2F:→ Eventis:XD...虽然这是compiler玩出来的XD 61.62.49.43 06/13
3F:推 khoguan:C有这种预设,C++不行。C99也不行。220.130.208.166 06/14
※ 编辑: khoguan 来自: 220.130.208.168 (08/24 14:53)