【问题标题】:Error: control may reach end of non-void function in C - RecursiveSearch错误:控制可能到达 C 中非空函数的结尾 - RecursiveSearch
【发布时间】:2014-07-21 14:52:18
【问题描述】:

我无法弄清楚为什么会发生此错误:错误:控制可能到达非无效函数的结尾。

我了解该错误意味着该函数可能会在没有返回任何内容的情况下到达末尾,但我无法弄清楚这是如何发生的。

我只是将一个非空数组传递给函数,如果这是任何安慰的话。

代码如下:

int recursivesearch(int values[], int lower, int upper, int value)
{
    int mid = (lower+upper)/2;
    if(lower>upper)
        return false;        
    if(value>values[mid])  
        recursivesearch(values,mid+1,upper,value);
    else if(value<values[mid])
        recursivesearch(values,lower,mid-1,value);
    else
        return mid;
}

由于最后一条语句只是一个 'else' 条件,它会确保返回,对吗?

【问题讨论】:

    标签: c controls


    【解决方案1】:

    由于最后一条语句只是一个“else”条件,它会确保返回,对吗?

    是的。但问题出在代码中的其他地方。请注意,函数的返回类型是 int 但您在 ifelse if 语句中都没有返回任何内容。改变

    if(value>values[mid])  
        recursivesearch(values,mid+1,upper,value);
    else if(value<values[mid])
        recursivesearch(values,lower,mid-1,value);  
    

    if(value>values[mid])  
        return recursivesearch(values,mid+1,upper,value);
    else if(value<values[mid])
        return recursivesearch(values,lower,mid-1,value);  
    

    请参阅wiki

    【讨论】:

      【解决方案2】:

      如果您查看 ifelse if 块,您实际上并没有从它们返回任何内容。您只需运行该函数并折腾返回值。你可能想要return recursivesearch(...)

      【讨论】:

        猜你喜欢
        • 2013-10-06
        • 1970-01-01
        • 1970-01-01
        • 2014-04-20
        • 1970-01-01
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多