我在c ++中有以下代码:
int fff ( int a , int b )
{
if (a>b )
return 0;
else a+b ;
}
Run Code Online (Sandbox Code Playgroud)
虽然我没有在'else'之后写'return'但它没有出错!在main()中我写的时候:
cout<<fff(1,2);
Run Code Online (Sandbox Code Playgroud)
它打印1?怎么会发生这种情况
可以解释一下吗?
这就是所谓的未定义行为.任何事情都可能发生.
C++不要求你总是在函数末尾返回一个值,因为它可以编写永远不会到达的代码:
int fff ( int a , int b )
{
if (a>b )
return 0;
else return a+b;
// still no return at end of function
// syntactically, just as bad as original example
// semantically, nothing bad can happen
}
Run Code Online (Sandbox Code Playgroud)
但是,编译器无法确定您是否永远不会到达函数的末尾,并且它可以做的最多就是发出警告.你应该避免在没有结束的情况下摔倒return.
如果你这样做,你可能会得到一个随机值,或者你可能会崩溃.