gpt4 book ai didi

c - 错误: control may reach end of non-void function

转载 作者:行者123 更新时间:2023-11-30 21:24:00 26 4
gpt4 key购买 nike

请有人能向我解释一下出了什么问题,为什么我会收到此错误:

error: control may reach end of non-void function

我正在尝试创建一个函数linearsearch(),它采用一个键和一个表,返回元素的索引(如果找到)。这很令人困惑;我是一名初学者,正在学习 cs50 在线类(class);我以前从未遇到过此错误。

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

最佳答案

在最后一个 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;

关于c - 错误: control may reach end of non-void function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com