首页 > 解决方案 > 带有 if 语句的函数没有返回值

问题描述

如果不满足条件,如何从函数返回。我正在尝试创建一个除法函数,它将返回除以 2 个数字的结果,但如果将其除以零,我该如何返回任何内容。

int div(int n1, int n2)
{
    if (n2 > 0)
    {
        return n1 / n2;
    }
}

编译时收到此警告:

警告:控制到达非无效函数的结尾

我明白这意味着什么,但是如果我不想返回值,我应该在 n2 为 0 的情况下输入什么;

标签: c++

解决方案


如果一个函数有返回类型,它必须返回something。因此,您可以:

返回函数和调用者同意表示“非值”的标记值,例如:

int div(int n1, int n2)
{
    if (n2 != 0)
    {
        return n1 / n2;
    }
    else
    {
        return -1; // or whatever makes sense for your use-case...
    }
}

如果没有可以使用的标记值,则可以使用std::optional(仅限 C++17 及更高版本),例如:

#include <optional>

std::optional<int> div(int n1, int n2)
{
    if (n2 != 0)
    {
        return n1 / n2;
    }
    else
    {
        return std::nullopt;
    }
}

或者,您可以更改函数以使用输出参数和bool返回值,例如:

bool div(int n1, int n2, int &result)
{
    if (n2 != 0)
    {
        result = n1 / n2;
        return true;
    }
    else
    {
        return false;
    }
}

否则,您将只需要throw一个例外,例如:

#include <stdexcept>

int div(int n1, int n2)
{
    if (n2 == 0)
    {
        throw std::invalid_argument("n2 must not be 0");
    }
    return n1 / n2;
}

推荐阅读