I cannot figure out why this error is happening: error: control may reach end of non-void function
Here is the code:
bool search(int value, int values[], int n) {
if (n < 1) {
return false;
}
for (int i = 0; i < n; i++) {
if (values[i] == value) {
return true;
break;
}
else {
return false;
}
}
}
I understand that the error means that the function may reach the end without returning anything, but I cannot figure out how that might happen.
Your code is equivalent to
Either you are in the habit of writing very simple things in an excessively complicated way, or that code doesn't do what you want it to do.
You are getting this error because if your
for
loop breaks due to breaking conditioni < n;
then it don't find anyreturn
statement afterfor
loop (see the below, I mentioned in code as comment).If
for
loop break due toi >= n
then control comes to the position where I commented and there is noreturn
statement present. Hence you are getting an error "reach end of non-void function in C".Additionally, remove
break
afterreturn
statement. ifreturn
executes then break never get chance to execute and break loop.Check your compiler should give you a warning - 'unreachable code'.
That compiler warning is not correct. Anyway, there is a bigger problem with your code:
This code only checks
values[0] == value
and then always returns. It's happening because of thatelse {return false;}
.You should write it this way:
Now, function checks entire
values
array and then returnsfalse
if there was no matches. But if it found a match, it will instantly returntrue
witout checking other elements.Also, compiler will not emit a warning for this code.
Some folks will probably hate this, but....