更新时间:2021-12-21 15:50:09
您的search
函数最后需要return
语句。此外,在返回
之后,您不需要break
语句。事实上,您根本不需要第一个if
或else
子句,您只需要:
Yoursearch
function requires areturn
statement at the end. Also, you do not require abreak
statement after areturn
. In fact you do not need the firstif
or theelse
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 thefor
loop is chaotic at best and doesn't need theelse
clause of theif
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 thoseif
statements? The compiler cannot figure that out and cannot assume thefor
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;
}
错误: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;
}
}
}