-2

请有人可以向我解释为什么会出现此错误:

error: control may reach end of non-void function

我正在尝试制作一个函数,该函数linearsearch()采用一个键和一个返回元素索引的表(如果找到)。这令人困惑;我是初学者,正在学习cs50在线课程;我以前从未遇到过这个错误。

#include <stdio.h>
#include <string.h>
#include <cs50.h>

int linearsearch(int key, int array[]);

int main(int argc , string argv[])
{ 
    int key = 0;
    int table[]={2,4,5,1,3};

    printf("%i is found in index %i\n",key,linearsearch(1,table));
}

int linearsearch(int key, int array[])
{
    for(int i = 0;i<5;i++){
        if(array[i] == key)
        {
             return i;
        }    
        else{
            return -1;
        }
    }
}
4

1 回答 1

2

在最后一个 for 循环中,无论哪种方式,您都从函数返回某些内容,因此不应该有任何问题(除了您的算法错误:如果找不到,它不应该立即返回)。

问题是:编译器不一定会看到您返回的数据是什么。它只是看到不会通过返回一些东西来结束你的日常工作。

大多数编译器可以找出简单的情况,例如:

   if (x) return 0; else return 1;
  // not returning anything in the main branch but ok as it's seen as unreachable
}

但在您的情况下,您有一个for包装返回指令的循环。编译器不是控制流分析器。他们做基本的事情,但肯定不是正式的执行。因此,有时他们会在您认为“正常”的地方发出警告。

无论如何,如前所述,您的算法不正确。只有当循环结束而没有找到任何东西时才返回 -1 来修复它。

在这种情况下,您可以修复错误和警告。因此,您会看到警告正确地检测到代码中的可疑内容。

固定代码:

for (int i = 0; i < 5; i++)
{
    if (array[i] == key)
    {
         // found return & exit loop
         return i;
    }    
}
// not found, end of loop: return -1
return -1;
于 2016-10-01T19:39:05.583 回答