且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

bo循环中的bool函数出错

更新时间:2021-12-21 15:50:09

您的 search 函数最后需要 return 语句。此外,在返回之后,您不需要 break 语句。事实上,您根本不需要第一个 if else 子句,您只需要:

Your search function requires a return statement at the end. Also, you do not require a break statement after a return. In fact you do not need the first if or the else clause at all, all you need is:
bool search(int value, int values[], int n) 
{
    for (int a = 0; a < n; a++)
    {
        if ( values[a] == value)
        {
            return true;
        }
    }
    return false;
}


循环内的代码充其量只是混乱而不是需要 if 语句的 else 子句。您的函数不会在所有代码路径上返回值。如果循环完成而没有满足您在 if 语句中设置的任何条件,会发生什么?编译器无法弄清楚,并且不能假设 for 循环永远不会完成。



你应该重写这个用于设置返回值的代码,而不是直接从循环内部返回。例如:

Your code inside the for loop is chaotic at best and doesn't need the else clause of the if statement. Your function doesn't return a value on all code paths. What happens if the loop completes without satisfying any of the conditions you set in those if statements? The compiler cannot figure that out and cannot assume the for loop will never complete.

You should be rewriting this code to set a return value instead of just straight out returning from inside the loop. For example:
bool search(int value, int values[], int n) 
{
    // The default is to return false.
    bool returnValue = false;

    // Is the n parameter OK?
    if ( n >= 0)
    {
        // Yes, so execute the search.
        for (int a = 0; a < n; a++)
        {
            if (values[a] == value)
            {
                returnValue = true;
                break;
            }
        }
    }

    return returnValue;
}


Quote:

错误:helpers.c :43:1:错误:控件可能会达到非空函数的结束[-Werror,-Wreturn-type]} ^

Error: helpers.c:43:1: error: control may reach end of non-void function [-Werror,-Wreturn-type] } ^



您收到此错误消息,因为它可能达到函数的结尾没有遇到返回


You get this error message because it is possible to reach the end of the function without encountering a return

for (int a = 0; a < n; a++)
{
    if ( values[a] == value)
    {
        return true;
        break;
    }

    else
    {
        if ( a == n)
        {
            // This line will never execute because a is never equal to n inside the loop
            return false;
        }
    }
}