在返回值不是void的情况下,即必须有返回值的情况下,C++可以没有默认返回值,而Java必须有默认的返回值。
举一个简单的例子,max函数,在c++中,可以写作如下。
int max (int a,int b){
<span style="white-space:pre"> </span>if(a>b)
<span style="white-space:pre"> </span>return a;
<span style="white-space:pre"> </span>else if(a<b)
<span style="white-space:pre"> </span>return b;
}
当输入max(2,2)的情况下,编译并不报错,运行返回2。单步调试未执行任何一步,而是返回2,不能理解。
在java中,上述程序编译不能通过,java需要确定的return以防止程序员情况考虑不周而运行出错。
上述程序需改为以下,固定的return。
int max (int a,int b){
<span style="white-space:pre"> </span>if(a>b)
<span style="white-space:pre"> </span>return a;
<span style="white-space:pre"&