c++ - 在 int 返回函数中返回“false”

Chr*_*ris 3 c++ null return

我有一个 int 函数,它在数组中搜索一个值,如果找到该值,它返回数组中位置的值。如果未找到该值,我会简单地 return false; 将这给我与return 0;?相同的结果吗?我也想知道如果我这样做了会发生什么return NULL;

Geo*_*e T 5

与 PHP 和其他语言不同,C++ 类型不会即时更改。一种做你想做的事情的方法(如果某些东西不起作用,则返回 false,但如果它起作用则返回 int)将定义具有 bool 返回类型的函数,但还要在其中传递一个 int 引用 (int&)。您返回 true 或 false 并将引用分配给正确的值。然后,在调用者中,您查看是否返回了 true,然后使用该值。

bool DoSomething(int input, int& output)
{
    //Calculations here
    if(/*successful*/)
    {
        output = value;
        return true;
    }

    output = 0; //any value really
    return false;
}

// elsewhere
int x = 5;
int result = 0;

if(DoSomething(x, result))
{
    std::cout << "The value is " << result << std::endl;
}
else
{
    std::cout << "Something went wrong" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)