C++中的函数行为

Com*_*eer 1 c++ function

我有以下代码:

int Fun(int x, int y)
{
    if(x<y)
        return 1;
}
int main ()
{

    cout<<Fun(6,2)<<endl;
}
Run Code Online (Sandbox Code Playgroud)

这段代码的输出是6(x的值)!! 我不知道为什么这种行为......任何人都可以向我解释.

提前致谢.

Pie*_*aud 6

在这里你有一个未定义的行为,就像它已经说过.

正如C++ 11标准中所述:

6.6.3退货声明[stmt.return]

  1. [..]从函数末尾流出相当于没有值的返回; 这会导致值返回函数中的未定义行为.

说明:

int Fun(int x, int y)
{
    if ( x < y ) // if this condition is false, then no return statement
        return 1;
}
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

int Fun(int x, int y)
{
    if ( x < y )
    {
        return 1;
    }
    return 0;  // <-- Fix the error
}
Run Code Online (Sandbox Code Playgroud)

注意:你的编译器至少应该给你一个警告 ......你有没有忽略它?(类似"并非所有控制路径都返回值")