簡體   English   中英

帶有 if 語句的 function 沒有返回值

[英]No return value from function with if statment

如果不滿足條件,我如何從 function 返回。 我正在嘗試進行除法 function 它將返回除以 2 個數字的結果,但是如果將其除以零,我該如何返回任何內容。

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

編譯時收到此警告:

警告:控制到達非無效 function 的末尾

我明白這意味着什么,但是如果我不想返回值,我應該在 n2 為 0 的情況下輸入什么;

如果 function 有返回類型,它必須返回something 因此,您可以:

返回 function 和調用者同意表示“非值”的標記值,例如:

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;
    }
}

或者,您可以更改 function 以使用 output 參數和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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM