c++中为什么int main()调用void show()时没设定返回值也能正常执行

#include <iostream>
void show()
{
std::cout<<“新手”;
}
int main()
{
show();
}

第1个回答  2011-09-22
#include <iostream>
void show()
{
std::cout<<"beginning"<<std::endl;
}
int main()
{
show();
return 0;
}
第2个回答  2011-09-22
1. 一般函数 ,如果指定了函数有返回值,则必须在函数内部有返会值 ,负责编译器会报错;
若没有指定返回值,则编译器就假定你的function为void,并会有"'void' return type assumed"的警 告
2. 对于main函数,若是指定有返回值,但没返回,编译器默认会按void处理,并警告提示“'void' return type assumed”追问

我上面的那个小程序生成时没有任何警告和报错。并且可以正常运行

追答

你用的是什么编译器,你先clean 掉,重新编译一次试试;应该有,除非指定编译器忽略某些警告信息,另外,你把你的show的返回值改成int,在内部不要有返回值,试试看报错不?(肯定会报错)

追问

vs2010
把void改成int是报错没错,但是为什在int main()调用void show()时且在int main()中不编入返回值。编译器显示成功生成且能运行。效果和加入return 0;后一样。

追答

至于警告,是和编译器有关系,vc 6.0 会报告,vc7 不会报告,vs2010没试过,原因参考下面:
The int value returned by main(), if any, is the program 's return value to "the system. " If no value is returned, the system will receive a value indicating successful completion. A nonzero value from main() indicates failure.

第3个回答  2011-09-22
谁告诉你 函数一定要、必须要 有返回值追问

如果int 后面没写返回值是不是编译器自动会写入啊?

追答

只有 main函数 并且编译器 比较现代化 才会帮你 自动加上
return 0;

本回答被网友采纳
第4个回答  2011-09-22
应该1个waring
相似回答