我有以下代码:
int Fun(int x, int y)
{
if(x<y)
return 1;
}
int main ()
{
cout<<Fun(6,2)<<endl;
}
这段代码的输出是6(x的值)!!我不知道为什么会出现这种行为...任何人都可以向我解释一下。
提前致谢。
最佳答案
这里有一个 Undefined behavior就像已经说过的那样。
正如 C++11 标准中所述:
6.6.3 The return statement [stmt.return]
- [..] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
解释:
int Fun(int x, int y)
{
if ( x < y ) // if this condition is false, then no return statement
return 1;
}
如何解决这个问题?
int Fun(int x, int y)
{
if ( x < y )
{
return 1;
}
return 0; // <-- Fix the error
}
注意:您的编译器至少应该给您一个警告……您是否忽略了它? (类似于“并非所有控制路径都返回一个值”)
关于c++ - C++ 中的函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784594/